Responses
Sending Data
Hemlock tries its best to serialize data in the correct way, based on the data provided.
Basic types are cast to strings.
res.Data("string") // string
res.Data(1.24523) // 1.24523
res.Data(true) // true
Structs are serialized to JSON.
type User struct {
Name string `json:"name"`
}
res.Data(&User{Name: "Gregory"})
// {"name": "Gregory"}
Files (and all io.Readers) are streamed directly to the response.
f, _ := os.Open("myfile.txt")
res.Data(f)
Errors
Errors can be handled using the Error
method. This will return a 500
response
and render the default error page.
f, err := os.Open("foo.txt")
if err != nil {
return res.Error(err)
}
The default behavior can be overridden by setting things before calling Error
.
The following example overrides both status code and the response body so calling Error
will only log the error.
res.Status(400).Data("Bad Request").Error(err)
Rendering Views
Templates can be rendered using the Render
method.
res.View("name", "layout", map[string]string{"name": "Gregory"})
The last two arguments are both optional.
res.View("name", "", nil)
Cookies
Cookies
res.Cookie(&http.Cookie{
Name: "session_id",
Value: "123",
Expires: time.Now().Add(time.Hour * 24 * 7),
})
HTTP Headers
Headers can be set using the Header
method.
res.Data(`{"foo": "bar"}`).Header("Content-Type", "application/json")