json HTTP请求主体验证模式

加安赫瓦:

我正在尝试了解用于验证JSON正文的模式。

例如,

  // I have this struct
  type Program struct {
    ProgramKey string `json:"program_key" validate:"required"`
    Active     *bool     `json:"active" validate:"required"`
  }

  // json request body
  {
    "program_key" : "example-key",
    "active" : false
  }

我想在JSON解码错误消失之前运行请求验证。但是不确定这是否是最好的方法。

因为每当我解码时

   // json request body
   {
    "program_key" : "example-key",
    "active" : "false" // notice the string value here
   }
   json.NewDecoder(r.Body).Decode(&program);

如果使用者发送的字符串为false,则解码失败。因为JSON解码无法解码和分配请求。我不介意将其用作错误处理/验证的第一层。但鉴于我可以自定义错误消息。我不想向消费者公开API的基本细节。

我在这方面找不到好的模式。

kingkupps:

即使来自的错误json.Decode,根据错误的不同,您将结果解析为的结构可能仍然包含一些结果。从Go文档中,如果您尝试解析类型json.Decode错误的JSON字符串,则会返回type错误UnmarshalTypeError就像是:

package main

import (
    "encoding/json"
    "fmt"
)

type Program struct {
    ProgramKey string `json:"program_key"`
    Active     bool   `json:"active"`
}

func (p *Program) String() string {
    return fmt.Sprintf("&Program{ProgramKey: %s, Active: %t", p.ProgramKey, p.Active)
}

func ParseProgram(jsonStr string) (*Program, error) {
    var p *Program
    err := json.Unmarshal([]byte(jsonStr), &p)
    if err != nil {
        switch err.(type) {
        case *json.UnmarshalTypeError:
            // Maybe log this or build a debug message from it.
            fmt.Println(err)
        default:
            return p, err
        }
    }
    // Inspect P further since it might still contain valid info.
    // ...
    return p, nil
}

func main() {
    jsonStr := `
        {
            "program_key": "example-key",
            "active": "false"
        }
    `
    p, err := ParseProgram(jsonStr)
    if err != nil {
        panic(err)
    }

    fmt.Println(p)
}

产生:

json: cannot unmarshal string into Go struct field Program.active of type bool
&Program{ProgramKey: example-key, Active: false

请注意,pin main中仍然ProgramKey填充了该字段。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章