登录
首页 >  Golang >  Go问答

如何为一个端点实现多种身份验证?

来源:stackoverflow

时间:2024-03-16 08:57:31 395浏览 收藏

为单个端点实现多种身份验证有多种方法。一种方法是使用 JSON 请求主体中包含的字段类型来区分不同的请求类型。例如,如果一个请求包含一个名为 "foo" 的字段,则可以将其视为属于类型 "Foo",而包含一个名为 "bar" 的字段的请求则属于类型 "Bar"。另一种方法是使用 HTTP 标头或查询参数来指定请求类型。例如,可以将 "Content-Type" 标头设置为 "application/json; type=Foo" 或 "application/json; type=Bar",或者将查询参数 "type" 设置为 "Foo" 或 "Bar"。

问题内容

我想制作一个验证 api 来验证一组有关特定规则集的 json 请求。为此,我只想使用一个端点并调用与特定 json 结构相对应的函数。我知道 go 中没有方法重载,所以我有点困惑。

...

type requestBodyA struct {
    SomeField   string `json:"someField"`
    SomeOtherField  string `json:"someOtherField"`
}

type requestBodyB struct {
    SomeDifferentField   string `json:"someDifferentField"`
    SomeOtherDifferentField  string `json:"someOtherDifferentField"`
}



type ValidationService interface {
    ValidateRequest(ctx context.Context, s string) (err error)
}

type basicValidationService struct{}

...

因此,为了验证大量不同的 json 请求,为每个 json 请求创建结构是否更好?或者我应该动态创建它们?如果我只有一个端点,我如何知道发送的是哪一类请求?


解决方案


如果您有一个必须接受不同 json 类型的端点/rpc,您需要以某种方式告诉它如何区分它们。一种选择是:

type request struct {
  bodya *requestbodya
  bodyb *requestbodyb
}

然后,将这些字段适当地填充到容器 json 对象中。如果存在 bodya 密钥,则 json 模块将仅填充 bodya,否则保留 nil,依此类推。

这是一个更完整的示例:

type RequestBodyFoo struct {
    Name    string
    Balance float64
}

type RequestBodyBar struct {
    Id  int
    Ref int
}

type Request struct {
    Foo *RequestBodyFoo
    Bar *RequestBodyBar
}

func (r *Request) Show() {
    if r.Foo != nil {
        fmt.Println("Request has Foo:", *r.Foo)
    }
    if r.Bar != nil {
        fmt.Println("Request has Bar:", *r.Bar)
    }
}

func main() {
    bb := []byte(`
    {
        "Foo": {"Name": "joe", "balance": 4591.25}
    }
    `)

    var req Request
    if err := json.Unmarshal(bb, &req); err != nil {
        panic(err)
    }
    req.Show()

    var req2 Request
    bb = []byte(`
    {
        "Bar": {"Id": 128992, "Ref": 801472}
    }
    `)
    if err := json.Unmarshal(bb, &req2); err != nil {
        panic(err)
    }
    req2.Show()
}

另一种选择是使用地图更动态地完成此操作,但上面的方法可能就足够了。

到这里,我们也就讲完了《如何为一个端点实现多种身份验证?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>