似乎 go slice append (string) 在我将其渲染到模板时更改了所有项目(也当我将切片记录到终端时)我认为这是 golang 的事情,但我不确定 Django 模板
更新了代码,但我仍然对 互斥锁和常规 Html 模板有同样的问题
package main
import (
"log"
"sync"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html"
)
func main() {
engine := html.New("./views", ".html")
app := fiber.New(fiber.Config{
Views: engine,
})
type Whatever struct {
Whatever string `json:"whatever" form:"whatever"`
}
var (
itemsMu sync.RWMutex
items = []string{}
)
app.Get("/", func(c *fiber.Ctx) error {
itemsMu.RLock()
defer itemsMu.RUnlock()
return c.Render("index", fiber.Map{
"Title": "Hello, World!",
"Slice": items,
})
})
app.Post("/", func(c *fiber.Ctx) error {
w := new(Whatever)
if err := c.BodyParser(w); err != nil {
return err
}
itemsMu.Lock()
items = append(items, w.Whatever)
log.Println(items)
itemsMu.Unlock()
return c.Redirect("/")
})
log.Fatal(app.Listen(":3000"))
}