đĻ Json
Json marshalls the given data parameter with the json.Marshal function and writes the result with the given status code to the http.ResponseWriter The Content-Type header is set accordingly to application/json
func ExampleGet(request there.Request) there.Response {
user := map[string]string{
"firstname": "John",
"surname": "Smith",
}
return there.Json(status.OK, user)
}
When this handler gets called, the final rendered result will be
{"firstname":"John","surname":"Smith"}
If the json.Marshal fails with an error, then an Error with StatusInternalServerError will be returned, with the error format "json: json.Marshal: %v"
func Json(code int, data any) Response {
jsonData, err := json.Marshal(data)
if err != nil {
return Error(status.InternalServerError, fmt.Errorf("json: json.Marshal: %v", err))
}
return jsonResponse{code: code, data: jsonData}
}
JsonError
JsonError marshalls the given data parameter with the json.Marshal function and writes the result with the given status code to the http.ResponseWriter The Content-Type header is set accordingly to application/json
func ExampleJsonErrorGet(request there.Request) there.Response{
user := map[string]string{
"firstname": "John",
"surname": "Smith",
}
resp, err := there.JsonError(status.OK, user)
if err != nil {
return there.Error(status.InternalServerError, fmt.Errorf("something went wrong: %v", err))
}
return resp
}
When this handler gets called, the final rendered result will be
{"firstname":"John","surname":"Smith"}
If the json.Marshal fails with an error, then a nil response with a non-nil error will be returned to handle.
func JsonError(code int, data any) (Response, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
return jsonResponse{code: code, data: jsonData}, nil
}
type jsonResponse struct {
code int
data []byte
}
func (j jsonResponse) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(j.code)
rw.Header().Set(header.ContentType, ContentTypeApplicationJson)
_, err := rw.Write(j.data)
if err != nil {
log.Printf("jsonResponse: ServeHttp write failed: %v", err)
}
}