Documentation
¶
Overview ¶
A quick and easy way to setup a RESTful JSON API
Go-Json-Rest is a thin layer on top of net/http that helps building RESTful JSON APIs easily. It provides fast URL routing using a Trie based implementation, and helpers to deal with JSON requests and responses. It is not a high-level REST framework that transparently maps HTTP requests to procedure calls, on the opposite, you constantly have access to the underlying net/http objects.
Example:
package main
import (
"github.com/ant0ine/go-json-rest"
"net/http"
)
type User struct {
Id string
Name string
}
func GetUser(w *rest.ResponseWriter, req *rest.Request) {
user := User{
Id: req.PathParam("id"),
Name: "Antoine",
}
w.WriteJson(&user)
}
func main() {
handler := rest.ResourceHandler{}
handler.SetRoutes(
rest.Route{"GET", "/users/:id", GetUser},
)
http.ListenAndServe(":8080", &handler)
}
Note about the URL routing: Instead of using the usual "evaluate all the routes and return the first regexp that matches" strategy, it uses a Trie data structure to perform the routing. This is more efficient, and scales better for a large number of routes. It supports the :param and *splat placeholders in the route strings.
Index ¶
Constants ¶
const ( HeaderAccessControlAllowOrigin = `Access-Control-Allow-Origin` HeaderAccessControlAllowCredentials = `Access-Control-Allow-Credentials` HeaderAccessConrtolMaxAge = `Access-Control-Max-Age` HeaderAccessControlAllowMethods = `Access-Control-Allow-Methods` HeaderAccessControlAllowHeaders = `Access-Control-Allow-Headers` HeaderAccessControlExposeHeaders = `Access-Control-Expose-Headers` )
Variables ¶
This section is empty.
Functions ¶
func Error ¶
func Error(w *ResponseWriter, error string, code int)
Produce an error response in JSON with the following structure, '{"Error":"My error message"}' The standard plain text net/http Error helper can still be called like this: http.Error(w, "error message", code)
func NotFound ¶
func NotFound(w *ResponseWriter, r *Request)
Produce a 404 response with the following JSON, '{"Error":"Resource not found"}' The standard plain text net/http NotFound helper can still be called like this: http.NotFound(w, r.Request)
Types ¶
type CorsRequest ¶
type CorsResponseHeaders ¶
type Origin ¶
type Origin struct {
// Host which is allowed for cross origin request
// '*' sign has a special meaning allowing any origin to access this resource.
// HTTP authentication, client-side SSL certificates and cookies are not allowed to be sent in case of '*'
Host string
// Allows sending credntials using cors
AllowCredentials bool
// List of headers which are allowed to be exposed in cors response
ExposeHeaders []string
// Time in seconds for which preflights will be cached
MaxAge uint64
// List of headers allowed in cors request
AllowHeaders []string
// If this function is not nil it'll be called after populating CorsRequestInfo and filling default headers (this means it is possible to override them)
// If this function returns nil this will mean that request is forbidden.
// If this function is nil itself it will be silently ignored and response will contain default CORS headers
AccessControl func(info *CorsRequest, headers *CorsResponseHeaders) error
}
type Request ¶
type Request struct {
*http.Request
// map of parameters that have been matched in the URL Path.
PathParams map[string]string
}
Inherit from http.Request, and provide additional methods.
func (*Request) DecodeJsonPayload ¶
Read the request body and decode the JSON using json.Unmarshal
func (*Request) UriBase ¶
Returns a URL structure for the base (scheme + host) of the application, without the trailing slash in the host
type ResourceHandler ¶
type ResourceHandler struct {
// If true, and if the client accepts the Gzip encoding, the response payloads
// will be compressed using gzip, and the corresponding response header will set.
EnableGzip bool
// If true, the JSON payload will be written in one line with no space.
DisableJsonIndent bool
// If true, the status service will be enabled. Various stats and status will
// then be available at GET /.status in a JSON format.
EnableStatusService bool
// If true, when a "panic" happens, the error string and the stack trace will be
// printed in the 500 response body.
EnableResponseStackTrace bool
// If true, the record that is logged for each response will be printed as JSON
// in the log. Convenient for log parsing.
EnableLogAsJson bool
// If true, the handler does NOT check the request Content-Type. Otherwise, it
// must be set to 'application/json' if the content is non-null.
// Note: If a charset parameter exists, it MUST be UTF-8
EnableRelaxedContentType bool
// Custom logger, defaults to log.New(os.Stderr, "", log.LstdFlags)
Logger *log.Logger
// contains filtered or unexported fields
}
Implement the http.Handler interface and act as a router for the defined Routes. The defaults are intended to be developemnt friendly, for production you may want to turn on gzip and disable the JSON indentation.
func (*ResourceHandler) ServeHTTP ¶
func (self *ResourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
This makes ResourceHandler implement the http.Handler interface. You probably don't want to use it directly.
func (*ResourceHandler) SetOrigins ¶
func (self *ResourceHandler) SetOrigins(origins ...Origin)
func (*ResourceHandler) SetRoutes ¶
func (self *ResourceHandler) SetRoutes(routes ...Route) error
Define the Routes. The order the Routes matters, if a request matches multiple Routes, the first one will be used.
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
Inherit from an object implementing the http.ResponseWriter interface, and provide additional methods.
func (*ResponseWriter) WriteJson ¶
func (self *ResponseWriter) WriteJson(v interface{}) error
Encode the object in JSON, set the content-type header, and call Write.
type Route ¶
type Route struct {
// Any http method. It will be used as uppercase to avoid common mistakes.
HttpMethod string
// A string like "/resource/:id.json".
// Placeholders supported are:
// :param that matches any char to the first '/' or '.'
// *splat that matches everything to the end of the string
// (placeholder names should be unique per PathExp)
PathExp string
// Code that will be executed when this route is taken.
Func func(*ResponseWriter, *Request)
}
Used with SetRoutes.
func RouteObjectMethod ¶
func RouteObjectMethod(httpMethod string, pathExp string, objectInstance interface{}, objectMethod string) Route
Create a Route that points to an object method. It can be convenient to point to an object method instead of a function, this helper makes it easy by passing the object instance and the method name as parameters.
