Documentation
¶
Overview ¶
Package handler provide new signature for handling http request.
Motivation ¶
The standard signature for handling http request is:
func(http.ResponseWriter, *http.Request)
it is not convenience to write branching inside it.
So we create new signature for handling http request
func h(r *http.Requset) handler.Response
Consider the following:
func h(w http.ResponseWriter, r *http.Request) {
if ... {
http.Error(w, "some error 1", 500)
return // it will be disaster if we forget this return
}
...
if ... {
http.Error(w, "some error 2", 500)
return // it will be disaster if we forget this return
}
...
fmt.Fprintln(w, "some data")
}
Now we can write it like this:
func h(r *http.Requset) handler.Response {
if ... {
return defresponse.Text(500, "some error 1")
}
...
if ... {
return defresponse.Text(500, "some error 2")
}
...
return defresponse.Text(200, "some data") // we can't forget this, because it'll be compile error if there is no `return`
}
Then use Of function to get old signature back
http.ListenAndServe(":8080", handler.Of(h))
Example ¶
package main
import (
"net/http"
"github.com/payfazz/go-handler"
"github.com/payfazz/go-handler/defresponse"
)
func main() {
http.HandleFunc("/hello", handler.Of(func(r *http.Request) handler.Response {
return defresponse.Text(200, "Hello")
}))
http.HandleFunc("/hello-with-header", handler.Of(func(r *http.Request) handler.Response {
return handler.MergeHeader(http.Header{
"Test-Header": {"test header value"},
},
defresponse.Text(200, "Hello"),
)
}))
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response representation.
func MergeHeader ¶
MergeHeader is used to add extra header to the response.
see Example for how to use this function.
func New ¶
func New(handler http.HandlerFunc) Response
New return Response that will be handled by handler.
You should use defresponse package. Use this function if defresponse is not enough for you.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package defresponse provide common way to create Response.
|
Package defresponse provide common way to create Response. |
Click to show internal directories.
Click to hide internal directories.