根据结构字段设置 Golang 的 HTTP 响应代码

huangapple go评论67阅读模式
英文:

Golang set http response code based on struct field

问题

在我编写的API中,我有一个错误结构体,它可以转换为JSON格式。当API发生错误时,它会返回该结构体,并将HTTP响应代码设置为相应的值。

type PodsError struct {
    ErrorCode       int     `json:"error_code"`
    CallingFunction string  `json:"calling_function"`
    Message         string  `json:"error_message"`
}

type PodsErrorWrapper struct {
    Error   PodsError   `json:"error"`
}

目前,每次我编写结构体时,我还要写一个头部,但我不喜欢看到这么多重复的代码。

error := PodsError{http.StatusNotFound, "Calling Func", "Message"}
response.WriteHeader(error.ErrorCode)
response.WriteEntity(PodsErrorWrapper{error})

是否有可能将WriteHeader调用移动到每次将错误传递给WriteEntity()时调用的某个函数中?我想应该有一个我可以为PodsErrorWrapper实现的函数,可以将HTTP状态设置为ErrorCode字段的值。

编辑:抱歉,我忘记提到,我正在使用go-restful包(github.com/emicklei/go-restful)。

英文:

Within an api I'm writing I have an error struct which marshals to json. When the api has an error it returns the struct and I set the http response code to be the appropriate value.

type PodsError struct {
    ErrorCode 		int 	`json:"error_code"`
    CallingFunction string 	`json:"calling_function"`
    Message			string 	`json:"error_message"`
}

type PodsErrorWrapper struct {
    Error 	PodsError 	`json:"error"`
}

Right now every time I write the struct I also write a header, but I don't like the amount of duplicate code I am seeing.

error := PodsError{http.StatusNotFound, "Calling Func", "Message"}
response.WriteHeader(error.ErrorCode)
response.WriteEntity(PodsErrorWrapper{error})

Is it possible to move the WriteHeader call to something that gets called whenever I pass the error to WriteEntity()? I figure there has to be a function I could implement for a PodsErrorWapper where I could just set the http status to be whatever the ErrorCode field is.

Edit: Sorry I forgot to mention, I am using the go-restful package (github.com/emicklei/go-restful)

答案1

得分: 1

你可以自己创建一个函数:

func writeEntity(r *restful.Response, value interface{}) error {
    // 如果 value 是一个错误
    if perr, ok := value.(PodsError); ok {
        r.WriteHeader(perr.ErrorCode)
        // 重新赋值 value,以便它被包装为 `{"error": value}`
        value = struct {
            Error PodsError `json:"error"`
        }{perr}
    }
    return r.WriteEntity(value)
}

然后在调用时始终使用该函数而不是 response.WriteEntity

writeEntity(response, PodsError{http.StatusNotFound, "Calling Func", "Message"})
英文:

You can make your own function:

func writeEntity(r *restful.Response, value interface{}) error {
    // if value is an error
	if perr, ok := value.(PodsError); ok {
		r.WriteHeader(perr.ErrorCode)
        // reassign value so it gets wrapped: `{"error": value}`
		value = struct {
			Error PodsError `json:"error"`
		}{perr}
	}
	return r.WriteEntity(value)
}

Then just always call that instead of response.WriteEntity:

writeEntity(response, PodsError{http.StatusNotFound, "Calling Func", "Message"})

huangapple
  • 本文由 发表于 2015年5月2日 03:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/29993365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定