在我的Golang代码中,CSRF使用NoSurf.这是来自Trevor Sawler的Golang课程,第8.2节.如果有什么不同的话,我决定用Bootstrap 5代替教程的Bootstrap 4.我的代码可以在here中找到.要激活Web服务器,我使用go run ./cmd/web/*.go
.因此,在cmd\web\routes.go
中,localhost:8080/search-availability
页提供了以下内容:
mux.Get("/search-availability", handlers.Repo.Availability)
mux.Post("/search-availability", handlers.Repo.AvailabilityPost)
在pkg\handlers\handlers.go
人中,我有:
func (m *Repository) Availability(w http.ResponseWriter, r *http.Request) {
log.Println("Availability")
render.RenderTemplate(w, r, "search-availability.page.tmpl", &models.TemplateData{})
}
func (m *Repository) AvailabilityPost(w http.ResponseWriter, r *http.Request) {
log.Println("Before Write")
w.Write([]byte("Posted to search-availability"))
log.Println("After Write")
}
在pkg\render\render.go
人中,我有:
func AddDefaultData(td *models.TemplateData, r *http.Request) *models.TemplateData {
td.CsrfToken = nosurf.Token(r)
return td
}
在pkg\models\templatedata.go
人中,我有:
type TemplateData struct {
StringMap map[string]string
IntMap map[string]int
FloatMap map[string]float64
Data map[string]interface{}
CsrfToken string
Flash string
Error string
}
在templates\search-availability.page.tmpl
内,我在第13行有:
<input type="text" name="csrf_token" value="{{.CsrfToken}}">
从localhost:8080/search-availability
页面中 Select 开始和结束日期后,单击Search Availability
按钮总是会得到400 Bad Request
,如下所示.
从终端上,我可以看到代码从未输入AvailabilityPost
:
2023/03/12 19:06:48 Hit the page
2023/03/12 19:06:48 Availability
2023/03/12 19:06:51 Hit the page
但是,如果我这样禁用cmd\web\routes.go
内部的nosurf
:
func routes(app *config.AppConfig) http.Handler {
mux := chi.NewRouter()
mux.Use(middleware.Recoverer)
mux.Use(WriteToConsole)
// mux.Use(NoSurf)
mux.Use(SessionLoad)
...
mux.Get("/search-availability", handlers.Repo.Availability)
mux.Post("/search-availability", handlers.Repo.AvailabilityPost)
...
fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))
return mux
}
浏览器显示一条成功的帖子:
Posted to search-availability
终端还确认:
2023/03/12 19:19:46 Hit the page
2023/03/12 19:19:46 Availability
2023/03/12 19:19:48 Hit the page
2023/03/12 19:19:48 Before Write
2023/03/12 19:19:48 After Write
谁能指出我做错了什么?我没有像教程中看到的那样得到一个成功的帖子.这些material 有点过时了,但我看不出这有什么问题.