By default Celerity outputs other data along with the response object returned by the route handler.
A response using the default structure would look like:
Handler
func MyHandler(c celerity.Context) celerity.Response {
user := map[string]interface{}{
"name": "Alice",
"age": 19
}
return c.R(user)
}
Response JSON
{
"requestId": "123e4567-e89b-12d3-a456-426655440000",
"success": true,
"error": null,
"data": {
"name": "Alice",
"age": 19
},
"meta": null
}
A number of things have been attached to the request:
- requestId – A request ID is a unique ID automatically generating for the request. RequestIds can be useful for tracking requests in logs.
- success - This value is false if an error or failure was returned from the server.
- error - The error message for errors returned with
Context.Error
orContext.Fail
. - data - This is the main response data that is returned from the handler.
- meta - This is data set in the context via Context.Meta and can be used for additional data about the request, such as the record count of a paged request.
Customizing the response structure
If the structure of responses doesnt work for your application you can control it completey. To do this you need to provide the server with a response adapter.
The adapter must conform to the ResponseAdapter interface by implementing a process function.
Process(Context, Response) ([]byte, error)
For reference the default adapter is implemented like this:
type JSONResponseAdapter struct{}
type JSONResponse struct {
RequestID string `json:"requestId"`
Success bool `json:"success"`
Error string `json:"error"`
Data interface{} `json:"data"`
Meta map[string]interface{} `json:"meta"`
}
func (ra *JSONResponseAdapter) Process(c Context, r Response) ([]byte, error) {
rObj := JSONResponse{
RequestID: c.RequestID,
Meta: r.Meta,
Data: r.Data,
}
if r.Error != nil {
rObj.Success = false
rObj.Error = r.Error.Error()
} else {
rObj.Success = true
}
return json.Marshal(rObj)
}
Using your adapter
Once you have written your own response adapter it can be set on the server.
svr := celerity.New()
svr.ResponseAdapter = MyAdapter{}
All requests use this adapter to render their response.