Documentation
¶
Overview ¶
Package http overrides net/http and gorilla/pat golang library to use JSON with Request and ResponseWriter in a more easy way.
Its purpose is to create web server sending and receiving JSON data in few lines.
Full Example
import (
"github.com/pikanezi/http"
"log"
)
type Object struct {
SomeField string `json:"someField,omitempty"`
}
func HelloWorldHandler(w http.ResponseWriter, r *http.Request) *http.Error {
object := &Object{"Hello World"}
if err := w.WriteJSON(object); err != nil {
return &http.Error{Error: err.Error()
}
}
func main() {
// NewRouter takes the domain to authorize it cross-domains requests
r := http.NewRouter()
r.Get("/hello/world", HelloWorldHandler)
log.Fatal(http.ListenAndServe(":8080", r)
}
Index ¶
- func Handle(route string, handler http.Handler)
- func ListenAndServe(addr string, handler http.Handler) error
- func Redirect(w ResponseWriter, r *Request, urlStr string, code int)
- func SetDebug(debug bool)
- func StatusText(code int) string
- type Error
- type HandlerFunc
- type Header
- type Request
- func (req *Request) ForEachFileHeader(key string, f func(int, *multipart.FileHeader) error) error
- func (req *Request) ForEachFileReader(key string, f func(int, io.Reader) error) error
- func (req *Request) GetAndReturnJSONObject(object interface{}) (interface{}, error)
- func (req *Request) GetFileReader(key string) (io.Reader, error)
- func (req *Request) GetJSONObject(object interface{}) error
- func (req *Request) GetXMLObject(object interface{}) error
- func (req *Request) URLParam(key string) string
- type Response
- type ResponseWriter
- type RouteHandler
- type Router
- func (router *Router) CustomHeader() Header
- func (router *Router) Delete(route string, h HandlerFunc) *RouteHandler
- func (router *Router) Get(route string, h HandlerFunc) *RouteHandler
- func (router *Router) Post(route string, h HandlerFunc) *RouteHandler
- func (router *Router) Put(route string, h HandlerFunc) *RouteHandler
- func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (router *Router) SetCustomHeader(customHeader Header)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Handle ¶
Handle registers the handler for the given pattern in the golang http DefaultServeMux. This should be avoided, use ListenAndServe instead.
func ListenAndServe ¶
ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Handler is typically the Router itself.
func Redirect ¶
func Redirect(w ResponseWriter, r *Request, urlStr string, code int)
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
Types ¶
type Error ¶
type Error struct {
Error string `json:"error,omitempty"`
HTTPCode int `json:"httpCode,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
}
Error is a type that must be used when returning from the Handlers.
func NewErrorAPI ¶
NewErrorAPI returns a new Error with a statusCode.
type HandlerFunc ¶
type HandlerFunc func(ResponseWriter, *Request) *Error
HandlerFunc must returns an Error that will be handled by the Router itself. See implementation of the ServeHTTP method of the Router.
type Request ¶
Request represents an HTTP request received by a server or to be sent by a client.
func CreateRequest ¶
CreateRequest a new Request from a classic Request.
func NewRequest ¶
NewRequest returns a new Request given a method, URL, and optional body.
func (*Request) ForEachFileHeader ¶
ForEachFileHeader calls the function f with every multipart.FileHeader contained in the provided form key. Opening and closing the file is the responsibility of the user.
func (*Request) ForEachFileReader ¶
ForEachFileReader calls the function f with every io.Reader contained in the provided form key. After every call to f, the file is close.
func (*Request) GetAndReturnJSONObject ¶
GetAndReturnJSONObject returns the JSON object from the body.
func (*Request) GetFileReader ¶
GetFileReader get the multiform body and returns it as a Reader.
func (*Request) GetJSONObject ¶
GetJSONObject just call json.Unmarshal to the body and put it in the object.
func (*Request) GetXMLObject ¶
GetXMLObject jus call xml.Unmarshal to the body and put it in the object.
type Response ¶
Response represents the response from an HTTP request.
func PostForm ¶
PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.
func PostJSON ¶
PostJSON issues a POST request of type "application/json" (the object will be marshaled as JSON) to the given URL.
func (*Response) GetAndReturnJSONObject ¶
GetAndReturnJSONObject returns an the JSON object from the body.
func (*Response) GetJSONObject ¶
GetJSONObject just call json.Unmarshal to the body and put it in the object.
func (*Response) GetXMLObject ¶
GetXMLObject jus call xml.Unmarshal to the body and put it in the object.
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
http.Hijacker
}
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
func CreateResponseWriter ¶
func CreateResponseWriter(r http.ResponseWriter) ResponseWriter
CreateResponseWriter create a new ResponseWriter from a classic ResponseWriter.
func (ResponseWriter) WriteError ¶
func (rw ResponseWriter) WriteError(customErr *Error) error
WriteError send an error using http.Error.
func (ResponseWriter) WriteJSON ¶
func (rw ResponseWriter) WriteJSON(object interface{}) error
WriteJSON marshal the Object and write it.
func (ResponseWriter) WriteSingleStringJSON ¶
func (rw ResponseWriter) WriteSingleStringJSON(key, value string)
WriteSingleStringJSON marshal a single key / value JSON and write it.
type RouteHandler ¶
RouteHandler contains the main Handler and the given mux.Route. When an interceptor has been given, it fires them. If an Error occurs in a Before interceptor, it stops any further interceptor and writes the Error to the client. If an Error occurs in the Handler, it fires the OnError interceptors and the After interceptors. Any Error occurring in a OnError or After interceptor is ignored.
func (*RouteHandler) After ¶
func (h *RouteHandler) After(handlers ...HandlerFunc) *RouteHandler
After add interceptors that must be run after the Request has been handled.
func (*RouteHandler) Before ¶
func (h *RouteHandler) Before(handlers ...HandlerFunc) *RouteHandler
Before add interceptors that must be run before the Request has been handled.
func (*RouteHandler) OnError ¶
func (h *RouteHandler) OnError(handlers ...HandlerFunc) *RouteHandler
OnError add interceptors that must be run when an Error occurs.
type Router ¶
Router embeds pat.Router. Router is a request router that implements a pat-like API. pat docs: http://godoc.org/github.com/bmizerany/pat
func NewRouter ¶
func NewRouter() *Router
NewRouter returns a new router with the given domain.
Example ¶
router := NewRouter()
router.Get("/", func(w ResponseWriter, r *Request) *Error {
w.WriteJSON("Hello!")
return nil
})
router.Get("/admin", func(w ResponseWriter, r *Request) *Error {
// do stuff
return nil
}).Before(func(w ResponseWriter, r *Request) *Error {
// check if user is an admin
return nil
})
router.Post("/upload", func(w ResponseWriter, r *Request) *Error {
if err := r.ForEachFile("file", func(index int, reader io.Reader) error {
// Do something with the reader
return nil
}); err != nil {
return NewError(err, 400)
}
return nil
})
ListenAndServe(":8080", router)
func (*Router) CustomHeader ¶
CustomHeader returns the customHeaders of the router.
func (*Router) Delete ¶
func (router *Router) Delete(route string, h HandlerFunc) *RouteHandler
Delete registers a pattern with a handler for DELETE requests.
func (*Router) Get ¶
func (router *Router) Get(route string, h HandlerFunc) *RouteHandler
Get registers a pattern with a handler for GET requests.
func (*Router) Post ¶
func (router *Router) Post(route string, h HandlerFunc) *RouteHandler
Post registers a pattern with a handler for POST requests.
func (*Router) Put ¶
func (router *Router) Put(route string, h HandlerFunc) *RouteHandler
Put registers a pattern with a handler for PUT requests.
func (*Router) ServeHTTP ¶
func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP dispatches the handler registered in the matched route. It performs any hooks and add the domain registered in the Router to be allowed for cross-domain requests.
func (*Router) SetCustomHeader ¶
SetCustomHeader set the customHeader of the router.