goweb/api/api.go

50 lines
1.0 KiB
Go

package api
import (
"encoding/json"
"fmt"
"net/http"
)
// Response is a JSON encoded HTTP response body
type Response struct {
Error *Error `json:"error,omitempty"`
Data interface{} `json:"data,omitempty"`
}
type ErrorCode string
// Error is a JSON encoded error
type Error struct {
Code ErrorCode `json:"code"`
Data interface{} `json:"data,omitempty"`
}
func (e *Error) Error() string {
return fmt.Sprintf("api-error: %s", e.Code)
}
func DataResponse(w http.ResponseWriter, status int, data interface{}) {
response(w, status, &Response{
Data: data,
}, false)
}
func ErrorResponse(w http.ResponseWriter, status int, code ErrorCode, data interface{}) {
response(w, status, &Response{
Error: &Error{code, data},
}, false)
}
func response(w http.ResponseWriter, status int, res *Response, conventional bool) {
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)
}
}