Documentation ¶
Index ¶
- Constants
- Variables
- func GetSecureCookie(ctx *Context) *securecookie.SecureCookie
- func JSONRequest(method, url string, reqData, respData interface{}) (err error)
- func TryCompressed(ctx *Context, fname string) error
- type AutoCertHosts
- type CertPair
- type Context
- func (ctx *Context) BindJSON(out interface{}) error
- func (ctx *Context) BindJSONP(val interface{}) (cb string, err error)
- func (ctx *Context) ClientIP() string
- func (ctx *Context) CloseBody() error
- func (ctx *Context) ContentType() string
- func (ctx *Context) Done() bool
- func (ctx *Context) EnableGzip(level int)
- func (ctx *Context) File(fp string) error
- func (ctx *Context) Get(key string) interface{}
- func (ctx *Context) GetCookie(name string) (out string, ok bool)
- func (ctx *Context) GetCookieValue(name string, valDst interface{}) error
- func (ctx *Context) JSON(code int, indent bool, v interface{}) error
- func (ctx *Context) JSONP(code int, callbackKey string, v interface{}) (err error)
- func (ctx *Context) MultipartReader() (*multipart.Reader, error)
- func (ctx *Context) Next() Response
- func (ctx *Context) NextHandler() Response
- func (ctx *Context) NextMiddleware() Response
- func (ctx *Context) Param(key string) string
- func (ctx *Context) Path() string
- func (ctx *Context) Printf(code int, contentType, s string, args ...interface{}) (int, error)
- func (ctx *Context) Query(key string) string
- func (ctx *Context) QueryDefault(key, def string) string
- func (ctx *Context) Read(p []byte) (int, error)
- func (ctx *Context) RemoveCookie(name string)
- func (ctx *Context) ReqHeader() http.Header
- func (ctx *Context) Set(key string, val interface{})
- func (ctx *Context) SetContentType(typ string)
- func (ctx *Context) SetCookie(name string, value interface{}, domain string, forceHTTPS bool, ...) (err error)
- func (ctx *Context) Status() int
- func (ctx *Context) Write(p []byte) (int, error)
- func (ctx *Context) WriteHeader(s int)
- func (ctx *Context) WriteReader(contentType string, r io.Reader) (int64, error)
- type Error
- type Group
- type Handler
- func AllowCORS(methods, headers, origins []string, groups ...Group) Handler
- func FromHTTPHandler(h http.Handler) Handler
- func FromHTTPHandlerFunc(h http.HandlerFunc) Handler
- func Gzip(level int) Handler
- func LogRequests(logJSONRequests bool) Handler
- func SecureCookie(hashKey, blockKey []byte) Handler
- func StaticDir(dir, paramName string) Handler
- func StaticDirStd(prefix, dir string, allowListing bool) Handler
- func StaticDirWithLimit(dir, paramName string, limit int) Handler
- type JSONPResponse
- type JSONResponse
- type M
- type MultiError
- type Option
- func MaxHeaderBytes(v int) Option
- func ReadTimeout(v time.Duration) Option
- func SetErrLogger(v *log.Logger) Option
- func SetKeepAlivePeriod(p time.Duration) Option
- func SetNoCatchPanics(enable bool) Option
- func SetOnReqDone(fn router.OnRequestDone) Option
- func SetProfileLabels(enable bool) Option
- func SetRouterOptions(v *router.Options) Option
- func WriteTimeout(v time.Duration) Option
- type Options
- type Response
- type Server
- func (g Server) AddRoute(method, path string, handlers ...Handler) error
- func (s *Server) Addrs() (out []string)
- func (s *Server) AllowCORS(path string, allowedMethods ...string) error
- func (s *Server) Close() error
- func (s *Server) Closed() bool
- func (g Server) DELETE(path string, handlers ...Handler) error
- func (g Server) GET(path string, handlers ...Handler) error
- func (g Server) Group(name, path string, mw ...Handler) Group
- func (s *Server) Logf(f string, args ...interface{})
- func (g Server) POST(path string, handlers ...Handler) error
- func (g Server) PUT(path string, handlers ...Handler) error
- func (g Server) Routes() [][3]string
- func (s *Server) Run(addr string) error
- func (s *Server) RunAutoCert(certCacheDir string, domains ...string) error
- func (s *Server) RunTLS(addr string, certPairs []CertPair) error
- func (s *Server) RunTLSAndAuto(certCacheDir string, certPairs []CertPair, hosts *AutoCertHosts) error
- func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (s *Server) SetKeepAlivesEnabled(v bool)
- func (s *Server) Shutdown(timeout time.Duration) error
- func (g Server) Static(path, localPath string, allowListing bool) error
- func (g Server) StaticFile(path, localPath string) error
- func (g Server) Use(mw ...Handler)
- type XMLResponse
Constants ¶
const ( MimeJSON = "application/json; charset=utf-8" MimeXML = "application/xml; charset=utf-8" MimeJavascript = "application/javascript; charset=utf-8" MimeHTML = "text/html; charset=utf-8" MimePlain = "text/plain; charset=utf-8" MimeBinary = "application/octet-stream" )
Common mime-types
Variables ¶
var ( // ErrDir is Returned from ctx.File when the path is a directory not a file. ErrDir = errors.New("file is a directory") // ErrInvalidURL gets returned on invalid redirect urls. ErrInvalidURL = errors.New("invalid redirect error") // ErrEmptyCallback is returned when a callback is empty ErrEmptyCallback = errors.New("empty callback") // ErrEmptyData is returned when the data payload is empty ErrEmptyData = errors.New("empty data") )
var DefaultOpts = Options{ WriteTimeout: time.Minute, ReadTimeout: time.Minute, MaxHeaderBytes: 16 << 10, KeepAlivePeriod: 3 * time.Minute, Logger: log.New(os.Stderr, "apiserv: ", 0), }
DefaultOpts are the default options used for creating new servers.
var EnableCacheResponse bool
Functions ¶
func GetSecureCookie ¶
func GetSecureCookie(ctx *Context) *securecookie.SecureCookie
GetSecureCookie returns the *securecookie.SecureCookie associated with the Context, or nil.
func JSONRequest ¶
func TryCompressed ¶
TryCompressed will try serving compressed files if they exist on the disk or use on the fly gzip.
Types ¶
type AutoCertHosts ¶
type AutoCertHosts struct {
// contains filtered or unexported fields
}
func NewAutoCertHosts ¶
func NewAutoCertHosts(hosts ...string) *AutoCertHosts
func (*AutoCertHosts) Contains ¶
func (a *AutoCertHosts) Contains(host string) bool
func (*AutoCertHosts) IsAllowed ¶
func (a *AutoCertHosts) IsAllowed(_ context.Context, host string) error
func (*AutoCertHosts) Set ¶
func (a *AutoCertHosts) Set(hosts ...string)
type Context ¶
type Context struct { http.ResponseWriter Req *http.Request Params router.Params // contains filtered or unexported fields }
Context is the default context passed to handlers it is not thread safe and should never be used outside the handler
func (*Context) BindJSON ¶
BindJSON parses the request's body as json, and closes the body. Note that unlike gin.Context.Bind, this does NOT verify the fields using special tags.
func (*Context) BindJSONP ¶
BindJSONP parses the request's callback and data search queries and closes the body
func (*Context) ClientIP ¶
ClientIP returns the current client ip, accounting for X-Real-Ip and X-forwarded-For headers as well.
func (*Context) ContentType ¶
ContentType returns the request's content-type.
func (*Context) EnableGzip ¶
func (*Context) GetCookieValue ¶
GetCookieValue unmarshals a cookie, only needed if you stored an object for the cookie not a string.
func (*Context) JSON ¶
JSON outputs a json object, it is highly recommended to return *Response rather than use this directly. calling this function marks the Context as done, meaning any returned responses won't be written out.
func (*Context) JSONP ¶
JSONP outputs a jsonP object, it is highly recommended to return *Response rather than use this directly. calling this function marks the Context as done, meaning any returned responses won't be written out.
func (*Context) MultipartReader ¶
MultipartReader is like Request.MultipartReader but supports multipart/*, not just form-data
func (*Context) Next ¶
Next is a QoL function that calls NextMiddleware() then NextHandler() if NextMiddleware() didn't return a response.
func (*Context) NextHandler ¶
NextHandler is a func to execute all the handlers in the group up until one returns a Response.
func (*Context) NextMiddleware ¶
NextMiddleware is a middleware-only func to execute all the other middlewares in the group and return before the handlers. will panic if called from a handler.
func (*Context) Printf ¶
Printf is a QoL function to handle outputing plain strings with optional fmt.Printf-style formating. calling this function marks the Context as done, meaning any returned responses won't be written out.
func (*Context) QueryDefault ¶
QueryDefault returns the query key or a default value.
func (*Context) RemoveCookie ¶
RemoveCookie deletes the given cookie and sets its expires date in the past.
func (*Context) Set ¶
Set sets a context value, useful in passing data to other handlers down the chain
func (*Context) SetContentType ¶
SetContentType sets the responses's content-type.
func (*Context) SetCookie ¶
func (ctx *Context) SetCookie(name string, value interface{}, domain string, forceHTTPS bool, duration time.Duration) (err error)
SetCookie sets an http-only cookie using the passed name, value and domain. Returns an error if there was a problem encoding the value. if forceSecure is true, it will set the Secure flag to true, otherwise it sets it based on the connection. if duration == -1, it sets expires to 10 years in the past, if 0 it gets ignored (aka session-only cookie), if duration > 0, the expiration date gets set to now() + duration. Note that for more complex options, you can use http.SetCookie(ctx, &http.Cookie{...}).
func (*Context) WriteHeader ¶
WriteHeader and Write are to implement ResponseWriter and allows ghetto hijacking of http.ServeContent errors, without them we'd end up with plain text errors, we wouldn't want that, would we? WriteHeader implements http.ResponseWriter
type Error ¶
type Error struct { Message string `json:"message,omitempty"` Field string `json:"field,omitempty"` IsMissing bool `json:"isMissing,omitempty"` }
Error is returned in the error field of a Response.
type Group ¶
type Group interface { // Use adds more middleware to the current group. // returning non-nil from a middleware returns early and doesn't execute the handlers. Use(mw ...Handler) // Group returns a sub-group starting at the specified path with this group's middlewares + any other ones. Group(name, path string, mw ...Handler) Group // Routes returns the current routes set. Routes() [][3]string // AddRoute adds a handler (or more) to the specific method and path // it is NOT safe to call this once you call one of the run functions AddRoute(method, path string, handlers ...Handler) error // GET is an alias for AddRoute("GET", path, handlers...). GET(path string, handlers ...Handler) error // PUT is an alias for AddRoute("PUT", path, handlers...). PUT(path string, handlers ...Handler) error // POST is an alias for AddRoute("POST", path, handlers...). POST(path string, handlers ...Handler) error // DELETE is an alias for AddRoute("DELETE", path, handlers...). DELETE(path string, handlers ...Handler) error // Static is a QoL wrapper to serving a directory. // If allowListing is true, it will fallback to using http.FileServer. Static(path, localPath string, allowListing bool) error // StaticFile is a QoL wrapper to serving a static file. StaticFile(path, localPath string) error }
Group represents a handler group.
type Handler ¶
Handler is the default server Handler In a handler chain, returning a non-nil breaks the chain.
func AllowCORS ¶
AllowCORS allows CORS responses. If methods is empty, it will respond with the requested method. If headers is empty, it will respond with the requested headers. If origins is empty, it will respond with the requested origin. will automatically install an OPTIONS handler to each passed group.
func FromHTTPHandler ¶
FromHTTPHandler returns a Handler from an http.Handler.
func FromHTTPHandlerFunc ¶
func FromHTTPHandlerFunc(h http.HandlerFunc) Handler
FromHTTPHandlerFunc returns a Handler from an http.Handler.
func LogRequests ¶
LogRequests is a request logger middleware. If logJSONRequests is true, it'll attempt to parse the incoming request's body and output it to the log.
func SecureCookie ¶
SecureCookie is a middleware to enable SecureCookies. For more details check `go doc securecookie.New`
func StaticDirStd ¶
StaticDirStd is a QoL wrapper for http.FileServer(http.Dir(dir)).
func StaticDirWithLimit ¶
StaticDirWithLimit returns a handler that handles serving static files. paramName is the path param, for example: s.GET("/s/*fp", StaticDirWithLimit("./static/", "fp", 1000)). if limit is > 0, it will only ever serve N files at a time. BUG: returns 0 size for some reason
type JSONPResponse ¶
type JSONPResponse struct { Callback string `json:"-"` JSONResponse }
JSONPResponse is the default standard api response
func NewJSONPErrorResponse ¶
func NewJSONPErrorResponse(callbackKey string, code int, errs ...interface{}) *JSONPResponse
NewJSONPErrorResponse returns a new error response. each err can be: 1. string or []byte 2. error 3. Error / *Error 4. another response, its Errors will be appended to the returned Response. 5. if errs is empty, it will call http.StatusText(code) and set that as the error.
func NewJSONPResponse ¶
func NewJSONPResponse(callbackKey string, data interface{}) *JSONPResponse
NewJSONPResponse returns a new success response (code 200) with the specific data
func (*JSONPResponse) WriteToCtx ¶
func (r *JSONPResponse) WriteToCtx(ctx *Context) error
WriteToCtx writes the response to a ResponseWriter
type JSONResponse ¶
type JSONResponse struct { Data interface{} `json:"data,omitempty"` Errors []Error `json:"errors,omitempty"` Code int `json:"code"` Success bool `json:"success"` Indent bool `json:"-"` }
JSONResponse is the default standard api response
func NewJSONErrorResponse ¶
func NewJSONErrorResponse(code int, errs ...interface{}) (r *JSONResponse)
NewJSONErrorResponse returns a new error response. each err can be: 1. string or []byte 2. error 3. Error / *Error 4. another response, its Errors will be appended to the returned Response. 5. MultiError 6. if errs is empty, it will call http.StatusText(code) and set that as the error.
func NewJSONResponse ¶
func NewJSONResponse(data interface{}) *JSONResponse
NewJSONResponse returns a new success response (code 200) with the specific data
func ReadJSONResponse ¶
func ReadJSONResponse(rc io.ReadCloser, dataValue interface{}) (r *JSONResponse, err error)
ReadJSONResponse reads a response from an io.ReadCloser and closes the body. dataValue is the data type you're expecting, for example:
r, err := ReadJSONResponse(res.Body, &map[string]*Stats{})
func (*JSONResponse) ErrorList ¶
func (r *JSONResponse) ErrorList() *tkErrors.ErrorList
ErrorList returns an errors.ErrorList of this response's errors or nil. Deprecated: handled using MultiError
func (*JSONResponse) WriteToCtx ¶
func (r *JSONResponse) WriteToCtx(ctx *Context) error
WriteToCtx writes the response to a ResponseWriter
type MultiError ¶
type MultiError []error
MultiError handles returning multiple errors.
func (MultiError) Error ¶
func (me MultiError) Error() string
func (*MultiError) Push ¶
func (me *MultiError) Push(err error)
Push adds an error to the MultiError slice if err != nil.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option is a func to set internal server Options.
func MaxHeaderBytes ¶
MaxHeaderBytes sets the max size of headers on the server. see http.Server.MaxHeaderBytes
func ReadTimeout ¶
ReadTimeout sets the read timeout on the server. see http.Server.ReadTimeout
func SetErrLogger ¶
SetErrLogger sets the error logger on the server.
func SetKeepAlivePeriod ¶
SetKeepAlivePeriod sets the underlying socket's keepalive period, set to -1 to disable socket keepalive. Not to be confused with http keep-alives which is controlled by apiserv.SetKeepAlivesEnabled.
func SetNoCatchPanics ¶
SetNoCatchPanics toggles catching panics in handlers.
func SetOnReqDone ¶
func SetOnReqDone(fn router.OnRequestDone) Option
func SetProfileLabels ¶
func SetRouterOptions ¶
SetRouterOptions sets apiserv/router.Options on the server.
func WriteTimeout ¶
WriteTimeout sets the write timeout on the server. see http.Server.WriteTimeout
type Options ¶
type Options struct { Logger *log.Logger RouterOptions *router.Options ReadTimeout time.Duration WriteTimeout time.Duration KeepAlivePeriod time.Duration MaxHeaderBytes int }
Options allows finer control over the apiserv
type Response ¶
Response represents a generic return type for http responses.
var ( RespMethodNotAllowed Response = NewJSONErrorResponse(http.StatusMethodNotAllowed) RespNotFound Response = NewJSONErrorResponse(http.StatusNotFound) RespForbidden Response = NewJSONErrorResponse(http.StatusForbidden) RespBadRequest Response = NewJSONErrorResponse(http.StatusBadRequest) RespOK Response = NewJSONResponse("OK") RespEmpty Response = &simpleResp{code: http.StatusNoContent} RespPlainOK Response = &simpleResp{code: http.StatusOK} RespRedirectRoot = Redirect("/", false) // Break can be returned from a handler to break a handler chain. // It doesn't write anything to the connection. // if you reassign this, a wild animal will devour your face. Break Response = &simpleResp{} )
Common responses
func PlainResponse ¶
PlainResponse returns SimpleResponse(200, contentType, val).
func Redirect ¶
Redirect returns a redirect Response. if perm is false it uses http.StatusFound (302), otherwise http.StatusMovedPermanently (302)
func RedirectWithCode ¶
RedirectWithCode returns a redirect Response with the specified status code.
func SimpleResponse ¶
SimpleResponse is a QoL wrapper to return a response with the specified code and content-type. val can be: nil, []byte, string, io.Writer, anything else will be written with fmt.Printf("%v").
type Server ¶
type Server struct { PanicHandler func(ctx *Context, v interface{}) NotFoundHandler func(ctx *Context) // contains filtered or unexported fields }
Server is the main server
func NewWithOpts ¶
NewWithOpts allows passing the Options struct directly
func (Server) AddRoute ¶
AddRoute adds a handler (or more) to the specific method and path it is NOT safe to call this once you call one of the run functions
func (*Server) Addrs ¶
Addrs returns all the listening addresses used by the underlying http.Server(s).
func (*Server) AllowCORS ¶
AllowCORS is an alias for s.AddRoute("OPTIONS", path, AllowCORS(allowedMethods...))
func (*Server) Close ¶
Close immediately closes all the active underlying http servers and connections.
func (Server) Routes ¶
func (g Server) Routes() [][3]string
Routes returns the current routes set. Each route is returned in the order of group name, method, path.
func (*Server) RunAutoCert ¶
RunAutoCert enables automatic support for LetsEncrypt, using the optional passed domains list. certCacheDir is where the certificates will be cached, defaults to "./autocert". Note that it must always run on *BOTH* ":80" and ":443" so the addr param is omitted.
func (*Server) RunTLSAndAuto ¶
func (s *Server) RunTLSAndAuto(certCacheDir string, certPairs []CertPair, hosts *AutoCertHosts) error
RunTLSAndAuto allows using custom certificates and autocert together. It will always listen on both :80 and :443
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP allows using the server in custom scenarios that expects an http.Handler.
func (*Server) SetKeepAlivesEnabled ¶
SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled.
func (*Server) Shutdown ¶
Shutdown gracefully shutsdown all the underlying http servers. You can optionally set a timeout.
func (Server) StaticFile ¶
type XMLResponse ¶
type XMLResponse struct { Data interface{} `json:"data,omitempty"` Errors []*Error `json:"errors,omitempty"` Code int `json:"code"` Success bool `json:"success"` Indent bool `json:"-"` }
XMLResponse is the default standard api response using xml from data
func NewXMLResponse ¶
func NewXMLResponse(data interface{}) *XMLResponse
func (*XMLResponse) WriteToCtx ¶
func (r *XMLResponse) WriteToCtx(ctx *Context) error
WriteToCtx writes the response to a ResponseWriter