It was my intention to use the HTTP status codes both in the header and the body of the two response structs. Bu that without setting the status code twice as function parameter and again for the struct to avoid redundancy.
The parameter response
of JSON()
is an interface to allow both structs to be accepted. The compiler throws the following exception:
response.Status undefined (type interface {} has no field or method Status)
because the response field must not have a status attribute. Is there an alternative way to avoid setting the status code twice?
type Response struct {
Status int `json:"status"`
Data interface{} `json:"data"`
}
type ErrorResponse struct {
Status int `json:"status"`
Errors []string `json:"errors"`
}
func JSON(rw http.ResponseWriter, response interface{}) {
payload, _ := json.MarshalIndent(response, "", " ")
rw.WriteHeader(response.Status)
...
}