卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35421本站已运行396

go中跨域自定义验证的问题

go中跨域自定义验证的问题

在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=<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,那么我需要将 CountryAge 提交到另一个 API,以查看该团队成员是否符合资格。< /p>

问题是我正在努力使用 reflect 库来访问 TeamMember 结构中的 CountryAge 字段。 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("%+vn", 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。

卓越飞翔博客
上一篇: 确保 Go 1.20 中编译时的严格可比性?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏