goweb/api/api.go

48 lines
977 B
Go
Raw Permalink Normal View History

package api
import (
"encoding/json"
"fmt"
"net/http"
)
// Response is a JSON encoded HTTP response body
type Response struct {
Error *Error `json:",omitempty"`
Data interface{} `json:",omitempty"`
}
type ErrorCode string
// Error is a JSON encoded error
type Error struct {
Code ErrorCode
Data interface{} `json:",omitempty"`
}
func (e *Error) Error() string {
return fmt.Sprintf("%s: %v", e.Code, e.Data)
}
func DataResponse(w http.ResponseWriter, status int, data interface{}) {
response(w, status, &Response{
Data: data,
})
}
func ErrorResponse(w http.ResponseWriter, status int, code ErrorCode, data interface{}) {
response(w, status, &Response{
Error: &Error{code, data},
})
}
func response(w http.ResponseWriter, status int, res *Response) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
if err := encoder.Encode(res); err != nil {
panic(err)
}
}