似乎go slice append(string)在我将其渲染到模板时更改了所有项(也在我将slice记录到终端时)我认为这是一个golang的事情,但我不确定with Django template
更新了代码,但我仍然有同样的问题with mutex and regular Html template
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"))
}
2条答案
按热度按时间vnzz0bqm1#
HTTP请求在不同的goroutine上提供。从请求中访问的作用域在请求之外的变量(例如您的
items
)必须同步。从不同的goroutine写变量是一种数据竞争和未定义的行为。
添加适当的同步,然后查看结果。
举例来说:
flvtvl502#
我知道,我有点迟到了,但我遇到了一个类似的问题(golang noob在这里),我建议如果有人遇到类似的问题,他们可以看看GoFiber的零分配
沿着这些线的东西应该工作(直接从文档):