Skip to main content

📝 Custom Http Response

Simply create your own HttpResponse to save time. However, if you need some inspiration, look into the response.go file.

For example, let us create a Msgpack response. By default, there does not provide a Msgpack response, because this would require a third-party dependency. But it is not much work to create your own Msgpack HttpResponse.

package main

import (
"github.com/Gebes/there/v2"
"github.com/vmihailenco/msgpack/v5"
"log"
)

//Msgpack takes a StatusCode and data which gets marshaled to Msgpack
func Msgpack(code int, data any) there.Response {
msgpackData, err := msgpack.Marshal(data) // marshal the data
if err != nil {
panic(err) // panic if the data was invalid. can be caught by Recoverer
}
return there.Headers(map[string]string{ // set proper content-type
header.ContentType: there.ContentTypeApplicationMsgpack,
}, there.Bytes(code, msgpackData))
}

func main() {
router := there.NewRouter()

router.
Get("/", Get)

err := router.Listen(8080)
if err != nil {
log.Fatalln("Could not listen to 8080", err)
}
}

func Get(request there.Request) there.Response {
return Msgpack(status.OK, map[string]string{ // now use the created response
"Hello": "World",
"How": "are you?",
})
}

There provides enough lower-level HttpResponses to build another one on top of it. At the bottom, we have a "Bytes" response, which writes the given bytes and the status code.
Wrapped around the Bytes response, you can find a Headers response, adding the ContentType header.

As you see, it is only a few lines of code to have a custom HttpResponse.