go - 如何分配特定的 http 状态代码?

标签 go

我编写了这个小 api,我正在使用验证器来验证请求字段,并且我在响应中传播错误但不是错误代码,我希望能够添加自定义错误消息并分配特定的状态代码。例如:如果传递了不正确的类型,我想发消息说已经传递了不正确的类型,状态码为 400,所需的缺失字段为 422,内部服务器错误为 500。我正在努力实现这一点。任何帮助将不胜感激。

type Trade struct {
    ClientTradeId string `json:"client_trade_id" validate:"nonzero"`
    Date          int    `json:"date" validate:"nonzero, min=20010101, max=21000101"`
    Quantity      string `json:"quantity" validate:"nonzero, regexp=^[-]?[0-9]*\\.?[0-9]+$"`
    Price         string `json:"price" validate:"nonnil, nonzero, regexp=^[-]?[0-9]*\\.?[0-9]+$"`
    Ticker        string `json:"ticker" validate:"nonzero, nonnil"`
}
type InternalTrade struct {
    Id string `json:"Id" validate:"nonzero"`
    Trade *Trade `json:"Trade"`
}

type TradeSubmitted struct {

    TradeId string `json:"TradeId" validate:"nonzero"`
    ClientTradeId string `json:"clientTradeId" validate:"nonzero"`

}

type Error struct {
    Message string `json:"Message"`
}


var trades []InternalTrade
var (
    tradeValidator = validator.NewValidator()
)
func createTrade(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    var trade Trade
    var tradeSubmitted TradeSubmitted

    json.NewDecoder(r.Body).Decode(&trade)
    if errs := tradeValidator.Validate(trade); errs != nil {
        json.NewEncoder(w).Encode(errs)
        return

    }
    internal := InternalTrade{
        Id: strconv.Itoa(rand.Intn(1000000)),
        Trade: &trade,
    }


    tradeSubmitted.ClientTradeId = trade.ClientTradeId
    tradeSubmitted.TradeId = internal.Id

    trades = append(trades, internal)

    json.NewEncoder(w).Encode(&tradeSubmitted)

}

最佳答案

恕我直言,请求验证应始终返回 400。
422 是为不同目的而设计的 - https://www.rfc-editor.org/rfc/rfc4918#section-11.2

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.


如果您的请求未通过验证,则意味着其语法不正确。
验证成功完成后,您可以进行额外检查,然后返回 422。
但是从不同的角度来看这个问题。
区分400和422真的那么重要吗?客户端软件(不是人类)会从中受益,这是否现实?
我在这里专注于软件,因为人们可以阅读消息,而代码对我们来说是多余的。
让我举一个例子,说明软件对状态码的正确 react 。
可靠的系统应该支持不同的错误代码,并区分重试有助于传递消息的情况与重试无用的情况,因为它总是失败(除非我们更改服务器代码)。通过返回 400,我们向客户端提示重试将无济于事。客户端可以在代码中实现分支并重试请求 500 并完成执行 400。
额外的 422 代码是否会增加任何值(value)?

关于go - 如何分配特定的 http 状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59604643/

相关文章:

go - 如果标准 golang big.Int 函数接受两个参数并返回一个值,为什么它要使用接收器?

go - 使用 Go 模块时如何导入本地包

go - Go 的内存占用是多少

html - 如何在 Go (Golang) 中将表单数据检索为 map (如 PHP 和 Ruby)

Ajax 请求未发送到 Go Web 服务器

git - 如何在 Go 中禁用 git clone 的凭据提示?

go - Git url映射到自定义域

go - 如何在非本地包中本地导入错误

去和多播(特别是 ospf)

go - 在go中将map的所有值转换为字符串