我正在嘗試使用驗(yàn)證器根據(jù)此結(jié)構(gòu)驗(yàn)證請求正文。但是在Postman中,在驗(yàn)證結(jié)構(gòu)時,它總是會拋出錯誤。我只希望在提出請求時需要所有值。package modeltype User struct { FeatureName string `json:"featureName" validate:"required"` Email string `json:"email" validate:"required"` CanAccess *bool `json:"can_access" validate:"required"`}我已嘗試將其作為Postman上的請求正文發(fā)送:// Request body{ "featureName": "crypto", "email": "test5@gmail.com", "can_access": true}// Response body{ "status": 422, "message": "Missing parameters featureName/can_access/email"}法典:package controllerimport ( "database/sql" "encoding/json" "errors" "net/http" "unicode/utf8" "github.com/yudhiesh/api/model" "gopkg.in/validator.v2" "github.com/yudhiesh/api/config")func InsertFeature(w http.ResponseWriter, r *http.Request) { var user model.User var response model.Response db := config.Connect() defer db.Close() // Decode body into user struct if err := json.NewDecoder(r.Body).Decode(&user); err != nil { response.Message = "Error" response.Status = http.StatusInternalServerError json.NewEncoder(w).Encode(response) return } else { // Validate struct to check if all fields are correct // Fails here! if err := validator.Validate(user); err != nil { response.Message = "Missing parameters featureName/can_access/email" response.Status = http.StatusUnprocessableEntity json.NewEncoder(w).Encode(response) return }
正確的請求正文被 Go 中的驗(yàn)證器視為無效
慕田峪7331174
2022-09-05 10:41:05