đŦ Message
Message builds a json response using the message parameter and writes the result with the given status code to the http.ResponseWriter The Content-Type header is set accordingly to application/json
func ExampleMessageGet(request there.Request) there.Response {
return there.Message(status.OK, "Hello there")
}
When this handler gets called, the final rendered result will be
{"message":"Hello there"}
For optimal performance the use of json.Marshal is avoided and the response body is built directly. With this way, there is no error that could occur.
func Message(code int, message string) Response {
var b strings.Builder
b.Grow(len(message))
for i := range message {
switch message[i] {
case '"':
b.WriteString("\\\"")
case '\'':
b.WriteString("\\'")
case '\v':
b.WriteString("\\v")
case '\f':
b.WriteString("\\f")
case '\r':
b.WriteString("\\r")
case '\n':
b.WriteString("\\n")
case '\t':
b.WriteString("\\t")
case '\b':
b.WriteString("\\b")
case '\a':
b.WriteString("\\a")
default:
b.WriteByte(message[i])
}
}
const (
jsonOpen = "{\"message\":\""
jsonClose = "\"}"
)
return jsonResponse{code: code, data: []byte(jsonOpen + b.String() + jsonClose)}
}