問題描述
如何將數據從控制器傳遞到 go lang 中的表單? (How can I pass data from controller to form in go lang?)
我有一個接收 http 請求的處理程序/控制器。
func UpdateHandler(request *http.Request) {
ID := mux.Vars(request)["ID"]
UpdateForm.Save(ID,db)
}
然後我有一個表單,我想處理數據並最終更新它。
type UpdateForm struct {
ID string `json:"type"`
}
func (UpdateForm) Save(db mongo.Database) {
id := ID
repository.Update(Id)
}
開始將打印出 undefined ID
如何確保表單從控制器獲取值?
參考解法
方法 1:
You can populate your form using data from the request. If your request contains a JSON encoded body than you could decode it into your form object like this:
package main
import (
"encoding/json"
"net/http"
"strings"
"fmt"
)
type UpdateForm struct {
ID string `json:"type"`
}
func main() {
req, _ := http.NewRequest(
"POST",
"http://example.com",
strings.NewReader(`{"type": "foo"}`),
)
var form *UpdateForm
json.NewDecoder(req.Body).Decode(&form)
fmt.Println(form.ID) // Output: foo
}
Or you can instantiate it directly like this:
func UpdateHandler(request *http.Request) {
ID := mux.Vars(request)["ID"]
form := &UpdateForm{ID: ID}
form.Save()
}
方法 2:
I think it has nothing to do with the handler, but your code isn't consistent. This line
UpdateForm.Save(ID,db)
The method Save()
takes two arguments, while the original method signature takes only a single mongo.Database
type argument.
Here is what I assume was your intention:
type UpdateForm struct {
ID string `json:"type"`
}
func (u UpdateForm) Save(db mongo.Database) {
id := u.ID
repository.Update(id)
}
// UpdateForm instance somewhere
var u = UpdateForm{}
func UpdateHandler(request *http.Request) {
u.ID := mux.Vars(request)["ID"]
u.Save(db)
}
(by thatgibbyguy、vially、Pandemonium)