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)