在Go語言開發中,跨域請求是一個常見的問題。跨域請求是指在瀏覽器中,通過JavaScript代碼向不同域名下的服務器發送請求。由于瀏覽器的同源策略限制,跨域請求默認是不被允許的。然而,在某些場景下,我們可能需要在跨域請求中進行自定義的驗證,以確保請求的安全性和準確性。本文將由php小編西瓜為您介紹如何在Go語言中解決跨域自定義驗證的問題,幫助您更好地應對跨域請求的挑戰。
問題內容
我正在嘗試學習 golang 自定義驗證,但遇到了很多麻煩。這是我一直在嘗試的代碼:
package main
import (
"reflect"
"github.com/go-playground/validator/v10"
"fmt"
)
type TeamMember struct {
Country string
Age int
DropShip bool `validate:"is_eligible"`
}
func CustomValidation(fl validator.FieldLevel) bool {
/*
if(DropShip == true) {
httpresponse = curl https://3rd-party-api.com/?country=&age=
return httpresponse.code == 200
}
return false
*/
b := fl.Parent()
fmt.Println(reflect.TypeOf(b))
fmt.Println(reflect.ValueOf(b))
c := reflect.ValueOf(b).Interface()
fmt.Println(c.(TeamMember))
fmt.Println("============")
return true
}
func main() {
var validate *validator.Validate
validate = validator.New(validator.WithRequiredStructEnabled())
_ = validate.RegisterValidation("is_eligible", CustomValidation)
teammember := TeamMember{"Canada", 34, true}
validate.Struct(teammember)
}
登錄后復制
您可以在代碼注釋中看到我嘗試的驗證邏輯…如果 DropShip 字段為 true,那么我需要將 Country 和 Age 提交到另一個 API,以查看該團隊成員是否符合資格。
問題是我正在努力使用 reflect 庫來訪問 TeamMember 結構中的 Country 和 Age 字段。 fmt.Println(c.(TeamMember)) 行使我的程序崩潰。
有人能給我一個如何訪問其他 TeamMember 字段的示例嗎?或者我的驗證方法是否違反了 golang 中驗證的慣用方式?
解決方法
在這種情況下,最好使用自定義結構級別驗證:
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type TeamMember struct {
Country string
Age int
DropShip bool
}
func TeamMemberStructLevelValidation(sl validator.StructLevel) {
teamMember := sl.Current().Interface().(TeamMember)
if teamMember.DropShip {
// submit the Country and Age to another API to see if this team member is eligible.
if teamMember.Country == "Canada" && teamMember.Age == 34 {
sl.ReportError(teamMember.Country, "country", "Country", "is_eligible", "")
sl.ReportError(teamMember.Age, "age", "Age", "is_eligible", "")
}
}
}
func main() {
validate := validator.New(validator.WithRequiredStructEnabled())
validate.RegisterStructValidation(TeamMemberStructLevelValidation, TeamMember{})
teamMember := TeamMember{"Canada", 34, true}
err := validate.Struct(teamMember)
fmt.Printf("%+v\n", err)
// Output:
// Key: 'TeamMember.country' Error:Field validation for 'country' failed on the 'is_eligible' tag
// Key: 'TeamMember.age' Error:Field validation for 'age' failed on the 'is_eligible' tag
}
登錄后復制
另請參閱包提供的示例:https://www.php.cn/link/fe41bb826b6a3cd35fe36744936400b9。






