gserv

package module
v1.1.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2024 License: MIT Imports: 35 Imported by: 1

Documentation

Index

Constants

View Source
const (
	MimeJSON       = "application/json"
	MimeEvent      = "text/event-stream"
	MimeMsgPack    = "application/msgpack"
	MimeXML        = "application/xml"
	MimeJavascript = "application/javascript"
	MimeHTML       = "text/html"
	MimePlain      = "text/plain"
	MimeBinary     = "application/octet-stream"
)

Common mime-types

View Source
const (
	// ErrDir is Returned from ctx.File when the path is a directory not a file.
	ErrDir = oerrs.String("file is a directory")

	// ErrInvalidURL gets returned on invalid redirect urls.
	ErrInvalidURL = oerrs.String("invalid redirect error")

	// ErrEmptyCallback is returned when a callback is empty
	ErrEmptyCallback = oerrs.String("empty callback")

	// ErrEmptyData is returned when the data payload is empty
	ErrEmptyData = oerrs.String("payload data is empty")
)

Variables

View Source
var (
	ErrBadRequest   = NewError(http.StatusBadRequest, "bad request")
	ErrUnauthorized = NewError(http.StatusUnauthorized, "unauthorized")
	ErrForbidden    = NewError(http.StatusForbidden, "the gates of time are closed")
	ErrNotFound     = NewError(http.StatusNotFound, "not found")
	ErrTeaPot       = NewError(http.StatusTeapot, "I'm a teapot")

	ErrInternal = NewError(http.StatusInternalServerError, "internal error")
	ErrNotImpl  = NewError(http.StatusNotImplemented, "not implemented")
)
View Source
var DefaultOpts = Options{
	WriteTimeout: time.Minute,
	ReadTimeout:  time.Minute,

	MaxHeaderBytes: 1 << 20,

	Logger: log.New(os.Stderr, "gserv: ", 0),
}

DefaultOpts are the default options used for creating new servers.

View Source
var DefaultPanicHandler = func(ctx *Context, v any, fr *oerrs.Frame) {
	msg, info := fmt.Sprintf("PANIC in %s %s: %v", ctx.Req.Method, ctx.Path(), v), fmt.Sprintf("at %s %s:%d", fr.Function, fr.File, fr.Line)
	ctx.Logf("%s (%s)", msg, info)
	resp := NewJSONErrorResponse(500, "internal server error")
	_ = ctx.Encode(500, resp)
}

Functions

func FilteredLogger added in v1.1.4

func FilteredLogger(flags int, msgs ...string) *log.Logger

func GetSecureCookie

func GetSecureCookie(ctx *Context) *securecookie.SecureCookie

GetSecureCookie returns the *securecookie.SecureCookie associated with the Context, or nil.

func H2Client added in v1.1.0

func H2Client() *http.Client

func JSONRequest

func JSONRequest(method, url string, reqData, respData any) (err error)

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 AutoCertOpts added in v1.1.3

type AutoCertOpts struct {
	Hosts autocert.HostPolicy `json:"hosts"`

	Eab *acme.ExternalAccountBinding `json:"eab"`

	Email    string `json:"email"`
	CacheDir string `json:"cacheDir"`

	DirectoryURL string `json:"directoryURL"`
}

type CacheableResponse

type CacheableResponse interface {
	Cached() Response
}

type CertPair

type CertPair struct {
	Cert  []byte   `json:"cert"`
	Key   []byte   `json:"key"`
	Roots [][]byte `json:"roots"`
}

CertPair is a pair of (cert, key) files to listen on TLS

func NewCertPair added in v1.1.3

func NewCertPair(certFile, keyFile string) (cp CertPair, err error)

type Codec

type Codec interface {
	ContentType() string
	Decode(r io.Reader, body any) error
	Encode(w io.Writer, v any) error
}
var DefaultCodec Codec = &JSONCodec{}

type Context

type Context struct {
	http.ResponseWriter
	Codec Codec

	Req *http.Request

	ReqQuery url.Values
	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) Bind

func (ctx *Context) Bind(out any) error

Bind parses the request's body as msgpack, and closes the body. Note that unlike gin.Context.Bind, this does NOT verify the fields using special tags.

func (*Context) BindCodec added in v1.1.0

func (ctx *Context) BindCodec(c Codec, out any) error

BindCodec parses the request's body as msgpack, and closes the body. Note that unlike gin.Context.BindCodec, this does NOT verify the fields using special tags.

func (*Context) BindJSON

func (ctx *Context) BindJSON(out any) error

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) BindMsgpack

func (ctx *Context) BindMsgpack(out any) error

BindMsgpoack parses the request's body as msgpack, and closes the body. Note that unlike gin.Context.Bind, this does NOT verify the fields using special tags.

func (*Context) BytesWritten added in v1.1.0

func (ctx *Context) BytesWritten() int

BytesWritten is the amount of bytes written from the body.

func (*Context) ClientIP

func (ctx *Context) ClientIP() string

ClientIP returns the current client ip, accounting for X-Real-Ip and X-forwarded-For headers as well.

func (*Context) CloseBody

func (ctx *Context) CloseBody() error

CloseBody closes the request body.

func (*Context) ContentType

func (ctx *Context) ContentType() string

ContentType returns the request's content-type.

func (*Context) Deadline added in v1.1.11

func (ctx *Context) Deadline() (time.Time, bool)

func (*Context) Done

func (ctx *Context) Done() <-chan struct{}

Done implements context.Context.

func (*Context) Encode

func (ctx *Context) Encode(code int, v any) error

func (*Context) EncodeCodec added in v1.1.0

func (ctx *Context) EncodeCodec(c Codec, code int, v any) error

func (*Context) Err added in v1.1.11

func (ctx *Context) Err() error

Err implements context.Context.

func (*Context) File

func (ctx *Context) File(fp string) error

File serves a file using http.ServeContent. See http.ServeContent.

func (*Context) Finished added in v1.1.11

func (ctx *Context) Finished() bool

Finished returns wither the context is marked as done or not.

func (*Context) Flush

func (ctx *Context) Flush()

Write implements http.Flusher

func (*Context) Get

func (ctx *Context) Get(key string) any

Get returns a context value

func (*Context) GetCookie

func (ctx *Context) GetCookie(name string) (out string, ok bool)

GetCookie returns the given cookie's value.

func (*Context) GetCookieValue

func (ctx *Context) GetCookieValue(name string, valDst any) error

GetCookieValue unmarshals a cookie, only needed if you stored an object for the cookie not a string.

func (*Context) JSON

func (ctx *Context) JSON(code int, indent bool, v any) error

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) LimitRead added in v1.1.8

func (ctx *Context) LimitRead(sz int64)

LimitRead limits the request body to the passed size.

func (*Context) LogSkipf

func (ctx *Context) LogSkipf(skip int, format string, v ...any)

func (*Context) Logf

func (ctx *Context) Logf(format string, v ...any)

func (*Context) Msgpack

func (ctx *Context) Msgpack(code int, v any) error

Msgpack outputs a msgp 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

func (ctx *Context) MultipartReader() (*multipart.Reader, error)

MultipartReader is like Request.MultipartReader but supports multipart/*, not just form-data

func (*Context) Next

func (ctx *Context) Next()

Next is a QoL function that calls NextMiddleware() then NextHandler() if NextMiddleware() didn't return a response.

func (*Context) NextHandler

func (ctx *Context) NextHandler()

NextHandler is a func to execute all the handlers in the group up until one returns a Response.

func (*Context) NextMiddleware

func (ctx *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) Param

func (ctx *Context) Param(key string) string

Param is a shorthand for ctx.Params.Get(name).

func (*Context) Path

func (ctx *Context) Path() string

Path is a shorthand for ctx.Req.URL.EscapedPath().

func (*Context) Printf

func (ctx *Context) Printf(code int, contentType, s string, args ...any) (int, error)

Printf is a QoL function to handle outputting plain strings with optional fmt.Printf-style formatting. calling this function marks the Context as done, meaning any returned responses won't be written out.

func (*Context) Query

func (ctx *Context) Query(key string) string

Query is a shorthand for ctx.Req.URL.Query().Get(key).

func (*Context) QueryDefault

func (ctx *Context) QueryDefault(key, def string) string

QueryDefault returns the query key or a default value.

func (*Context) Read

func (ctx *Context) Read(p []byte) (int, error)

Read is a QoL shorthand for ctx.Req.Body.Read. Context implements io.Reader

func (*Context) RemoveCookie

func (ctx *Context) RemoveCookie(name string)

RemoveCookie deletes the given cookie and sets its expires date in the past.

func (*Context) ReqHeader

func (ctx *Context) ReqHeader(key string) string

ReqHeader returns the request header.

func (*Context) Route added in v1.1.0

func (ctx *Context) Route() *router.Route

func (*Context) Set

func (ctx *Context) Set(key string, val any)

Set sets a context value, useful in passing data to other handlers down the chain

func (*Context) SetContentType

func (ctx *Context) SetContentType(typ string)

SetContentType sets the responses's content-type.

func (*Context) SetCookie

func (ctx *Context) SetCookie(name string, value any, 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) Status

func (ctx *Context) Status() int

Status returns last value written using WriteHeader.

func (*Context) Value added in v1.1.11

func (ctx *Context) Value(key any) any

Value implements context.Context.

func (*Context) Write

func (ctx *Context) Write(p []byte) (int, error)

Write implements http.ResponseWriter

func (*Context) WriteHeader

func (ctx *Context) WriteHeader(s int)

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

func (*Context) WriteReader

func (ctx *Context) WriteReader(contentType string, r io.Reader) (int64, error)

WriteReader outputs the data from the passed reader with optional content-type.

func (*Context) WriteString

func (ctx *Context) WriteString(p string) (int, error)

Write implements io.StringWriter

type Decoder

type Decoder interface {
	Decode(v any) error
}

type DummyResponseWriter added in v1.1.0

type DummyResponseWriter struct {
	// contains filtered or unexported fields
}

func (*DummyResponseWriter) Bytes added in v1.1.0

func (d *DummyResponseWriter) Bytes() []byte

func (*DummyResponseWriter) Header added in v1.1.0

func (d *DummyResponseWriter) Header() http.Header

func (*DummyResponseWriter) Status added in v1.1.0

func (d *DummyResponseWriter) Status() int

func (*DummyResponseWriter) Write added in v1.1.0

func (d *DummyResponseWriter) Write(b []byte) (int, error)

func (*DummyResponseWriter) WriteHeader added in v1.1.0

func (d *DummyResponseWriter) WriteHeader(v int)

type Encoder

type Encoder interface {
	Encode(v any) error
}

type Error

type Error struct {
	Caller  *callerInfo `json:"caller,omitempty"`
	Message string      `json:"message,omitempty"`
	Code    int         `json:"code,omitempty"`
}

func (Error) Error

func (e Error) Error() string

func (Error) Status

func (e Error) Status() int

type GenResponse

type GenResponse[CodecT Codec] struct {
	Data    any     `json:"data,omitempty"`
	Errors  []Error `json:"errors,omitempty"`
	Code    int     `json:"code"`
	Success bool    `json:"success"`
}

GenResponse is the default standard api response

func NewErrorResponse

func NewErrorResponse[CodecT Codec](code int, errs ...any) (r *GenResponse[CodecT])

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 NewResponse

func NewResponse[CodecT Codec](data any) *GenResponse[CodecT]

func (GenResponse[CodecT]) Cached

func (r GenResponse[CodecT]) Cached() Response

func (*GenResponse[CodecT]) ErrorList

func (r *GenResponse[CodecT]) ErrorList() *oerrs.ErrorList

ErrorList returns an errors.ErrorList of this response's errors or nil. Deprecated: handled using MultiError

func (GenResponse[CodecT]) Status

func (r GenResponse[CodecT]) Status() int

func (GenResponse[CodecT]) WriteToCtx

func (r GenResponse[CodecT]) WriteToCtx(ctx *Context) error

WriteToCtx writes the response to a ResponseWriter

type Group

type Group struct {
	// contains filtered or unexported fields
}

func (*Group) AddRoute

func (g *Group) AddRoute(method, path string, handlers ...Handler) Route

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 (*Group) DELETE

func (g *Group) DELETE(path string, handlers ...Handler) Route

DELETE is an alias for AddRoute("DELETE", path, handlers...).

func (*Group) DisableRoute added in v1.1.0

func (g *Group) DisableRoute(method, path string, disabled bool) bool

func (*Group) GET

func (g *Group) GET(path string, handlers ...Handler) Route

GET is an alias for AddRoute("GET", path, handlers...).

func (*Group) OPTIONS added in v1.1.0

func (g *Group) OPTIONS(path string, handlers ...Handler) Route

OPTIONS is an alias for AddRoute("OPTIONS", path, handlers...).

func (*Group) POST

func (g *Group) POST(path string, handlers ...Handler) Route

POST is an alias for AddRoute("POST", path, handlers...).

func (*Group) PUT

func (g *Group) PUT(path string, handlers ...Handler) Route

PUT is an alias for AddRoute("PUT", path, handlers...).

func (*Group) Routes

func (g *Group) Routes() [][3]string

Routes returns the current routes set. Each route is returned in the order of group name, method, path.

func (*Group) Static

func (g *Group) Static(path, localPath string, allowListing bool) Route

func (*Group) StaticFile

func (g *Group) StaticFile(path, localPath string) Route

func (*Group) SubGroup

func (g *Group) SubGroup(name, path string, mw ...Handler) *Group

SubGroup returns a sub-handler group based on the current group's middleware

func (*Group) Use

func (g *Group) Use(mw ...Handler)

Use adds more middleware to the current group.

type GroupType added in v1.1.0

type GroupType interface {
	AddRoute(method, path string, handlers ...Handler) Route
}

type HTTPError

type HTTPError interface {
	Status() int
	Error() string
}

func NewError

func NewError(status int, msg any) HTTPError

func NewErrorWithCaller

func NewErrorWithCaller(status int, msg string, skip int) HTTPError

type Handler

type Handler = func(ctx *Context) Response

Handler is the default server Handler In a handler chain, returning a non-nil breaks the chain.

func AllowCORS

func AllowCORS(methods, headers, origins []string, groups ...GroupType) Handler

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 CacheHandler

func CacheHandler(etag func(ctx *Context) string, ttlDuration time.Duration, handler Handler) Handler

func HTTPHandler

func HTTPHandler(h http.Handler) Handler

HTTPHandler returns a Handler from an http.Handler.

func HTTPHandlerFunc

func HTTPHandlerFunc(h http.HandlerFunc) Handler

FromHTTPHandlerFunc returns a Handler from an http.Handler.

func LogRequests

func LogRequests(logJSONRequests bool) Handler

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 ProxyHandler added in v1.1.0

func ProxyHandler(host string, pathFn func(ctx *Context, path string) (string, error)) Handler

func RateLimiter added in v1.1.7

func RateLimiter(ctx context.Context, limitKey LimitKeyFn, maxPerSecond, maxPerMinute, maxPerHour int, setHeaders bool) Handler

func SecureCookie

func SecureCookie(hashKey, blockKey []byte) Handler

SecureCookie is a middleware to enable SecureCookies. For more details check `go doc securecookie.New`

func StaticDir

func StaticDir(dir, paramName string) Handler

StaticDir is a shorthand for StaticDirWithLimit(dir, paramName, -1).

func StaticDirStd

func StaticDirStd(prefix, dir string, allowListing bool) Handler

StaticDirStd is a QoL wrapper for http.FileServer(http.Dir(dir)).

func StaticDirWithLimit

func StaticDirWithLimit(dir, paramName string, limit int) Handler

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 JSONCodec

type JSONCodec struct{ Indent bool }

func (JSONCodec) ContentType

func (JSONCodec) ContentType() string

func (JSONCodec) Decode

func (JSONCodec) Decode(r io.Reader, out any) error

func (JSONCodec) Encode

func (j JSONCodec) Encode(w io.Writer, v any) error

type JSONResponse

type JSONResponse = GenResponse[JSONCodec]

func NewJSONErrorResponse

func NewJSONErrorResponse(code int, errs ...any) *JSONResponse

func NewJSONResponse

func NewJSONResponse(data any) *JSONResponse

NewJSONResponse returns a new (json) success response (code 200) with the specific data

func ReadJSONResponse

func ReadJSONResponse(rc io.ReadCloser, dataValue any) (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{})

type LimitKeyFn added in v1.1.7

type LimitKeyFn = func(ctx *Context) string

type Limiter added in v1.1.7

type Limiter struct {
	// contains filtered or unexported fields
}

func NewLimiter added in v1.1.7

func NewLimiter(maxPerSecond, maxPerMinute, maxPerHour int) *Limiter

func (*Limiter) Allowed added in v1.1.7

func (l *Limiter) Allowed() (d time.Duration, err error)

Allowed returns the duration until the next action is allowed and an error if it's longer than 0

func (*Limiter) LastAction added in v1.1.7

func (l *Limiter) LastAction() (t time.Time)

func (*Limiter) RequestsLeft added in v1.1.7

func (l *Limiter) RequestsLeft() (perSecond, perMinute, perHour int64)

type Limiters added in v1.1.7

type Limiters struct {
	// contains filtered or unexported fields
}

func NewLimiters added in v1.1.7

func NewLimiters(ctx context.Context, maxPerSecond, maxPerMinute, maxPerHour int) *Limiters

func (*Limiters) Get added in v1.1.7

func (ls *Limiters) Get(key string) *Limiter

type M

type M map[string]any

func (M) ToJSON

func (m M) ToJSON(indent bool) string

ToJSON returns a string json representation of M, mostly for debugging.

type MixedCodec

type MixedCodec[Dec, Enc Codec] struct {
	// contains filtered or unexported fields
}

func (MixedCodec[Dec, Enc]) ContentType

func (m MixedCodec[Dec, Enc]) ContentType() string

func (MixedCodec[Dec, Enc]) Decode

func (m MixedCodec[Dec, Enc]) Decode(r io.Reader, out any) error

func (MixedCodec[Dec, Enc]) Encode

func (m MixedCodec[Dec, Enc]) Encode(w io.Writer, v any) error

type MsgpCodec

type MsgpCodec struct{}

func (MsgpCodec) ContentType

func (MsgpCodec) ContentType() string

func (MsgpCodec) Decode

func (MsgpCodec) Decode(r io.Reader, out any) error

func (MsgpCodec) Encode

func (c MsgpCodec) Encode(w io.Writer, v any) error

type MsgpResponse

type MsgpResponse = GenResponse[MsgpCodec]

func NewMsgpErrorResponse

func NewMsgpErrorResponse(code int, errs ...any) *MsgpResponse

func NewMsgpResponse

func NewMsgpResponse(data any) *MsgpResponse

NewMsgpResponse returns a new (msgpack) success response (code 200) with the specific data

type MultiError

type MultiError []error

MultiError handles returning multiple errors.

func (MultiError) Err

func (me MultiError) Err() error

Err returns nil if me is empty.

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 = func(opt *Options)

Option is a func to set internal server Options.

func MaxHeaderBytes

func MaxHeaderBytes(v int) Option

MaxHeaderBytes sets the max size of headers on the server. see http.Server.MaxHeaderBytes

func ReadTimeout

func ReadTimeout(v time.Duration) Option

ReadTimeout sets the read timeout on the server. see http.Server.ReadTimeout

func SetCatchPanics

func SetCatchPanics(enable bool) Option

SetNoCatchPanics toggles catching panics in handlers.

func SetErrLogger

func SetErrLogger(v *log.Logger) Option

SetErrLogger sets the error logger on the server.

func SetOnReqDone

func SetOnReqDone(fn router.OnRequestDone) Option

func SetProfileLabels

func SetProfileLabels(enable bool) Option

func SetRouterOptions

func SetRouterOptions(v *router.Options) Option

SetRouterOptions sets gserv/router.Options on the server.

func WriteTimeout

func WriteTimeout(v time.Duration) Option

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
	MaxHeaderBytes int

	CatchPanics bool
}

Options allows finer control over the gserv

type PanicHandler

type PanicHandler = func(ctx *Context, v any, fr *oerrs.Frame)

type PlainTextCodec

type PlainTextCodec struct{}

func (PlainTextCodec) ContentType

func (PlainTextCodec) ContentType() string

func (PlainTextCodec) Decode

func (PlainTextCodec) Decode(r io.Reader, out any) error

func (PlainTextCodec) Encode

func (PlainTextCodec) Encode(w io.Writer, v any) (err2 error)

type PlainTextResponse

type PlainTextResponse = GenResponse[PlainTextCodec]

func NewPlainErrorResponse

func NewPlainErrorResponse(code int, errs ...any) *PlainTextResponse

func NewPlainResponse

func NewPlainResponse(data any) *PlainTextResponse

NewJSONResponse returns a new (json) success response (code 200) with the specific data

type Response

type Response interface {
	Status() int
	WriteToCtx(ctx *Context) error
}

Response represents a generic return type for http responses.

var (
	RespMethodNotAllowed Response = NewJSONErrorResponse(http.StatusMethodNotAllowed).Cached()
	RespNotFound         Response = NewJSONErrorResponse(http.StatusNotFound).Cached()
	RespForbidden        Response = NewJSONErrorResponse(http.StatusForbidden).Cached()
	RespBadRequest       Response = NewJSONErrorResponse(http.StatusBadRequest).Cached()
	RespOK               Response = NewJSONResponse("OK").Cached()
	RespEmpty            Response = CachedResponse(http.StatusNoContent, "", nil)
	RespPlainOK          Response = CachedResponse(http.StatusOK, "", nil)
	RespRedirectRoot     Response = 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 = &cachedResp{code: -1}
)

Common responses

func CachedResponse

func CachedResponse(code int, contentType string, body any) Response

func File

func File(contentType, fp string) Response

File returns a file response. example: return File("plain/html", "index.html")

func PlainResponse

func PlainResponse(contentType string, body any) Response

func Redirect

func Redirect(url string, perm bool) Response

Redirect returns a redirect Response. if perm is false it uses http.StatusFound (302), otherwise http.StatusMovedPermanently (302)

func RedirectWithCode

func RedirectWithCode(url string, code int) Response

RedirectWithCode returns a redirect Response with the specified status code.

type Route

type Route = *router.Route

func Delete

func Delete[CodecT Codec, Resp any, HandlerFn func(ctx *Context) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func Get

func Get[CodecT Codec, Resp any, HandlerFn func(ctx *Context) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func JSONDelete

func JSONDelete[Resp any, HandlerFn func(ctx *Context) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func JSONGet

func JSONGet[Resp any, HandlerFn func(ctx *Context) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func JSONPatch

func JSONPatch[Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func JSONPost

func JSONPost[Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func JSONPut

func JSONPut[Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func MsgpDelete

func MsgpDelete[Resp any, HandlerFn func(ctx *Context) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func MsgpGet

func MsgpGet[Resp any, HandlerFn func(ctx *Context) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func MsgpPatch

func MsgpPatch[Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func MsgpPost

func MsgpPost[Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func MsgpPut

func MsgpPut[Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func Patch

func Patch[CodecT Codec, Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func Post

func Post[CodecT Codec, Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

func Put

func Put[CodecT Codec, Req, Resp any, HandlerFn func(ctx *Context, reqBody Req) (resp Resp, err error)](g GroupType, path string, handler HandlerFn, wrapResp bool) Route

type Server

type Server struct {
	Group

	PanicHandler
	NotFoundHandler func(ctx *Context)

	NoCompression bool // used by proxies
	// contains filtered or unexported fields
}

Server is the main server

func New

func New(opts ...Option) *Server

New returns a new server with the specified options.

func NewWithOpts

func NewWithOpts(opts *Options) *Server

NewWithOpts allows passing the Options struct directly

func (*Server) Addrs

func (s *Server) Addrs() (out []string)

Addrs returns all the listening addresses used by the underlying http.Server(s).

func (*Server) AllowCORS

func (s *Server) AllowCORS(path string, allowedMethods ...string)

AllowCORS is an alias for s.AddRoute("OPTIONS", path, AllowCORS(allowedMethods...))

func (*Server) Close

func (s *Server) Close() error

Close immediately closes all the active underlying http servers and connections.

func (*Server) Closed

func (s *Server) Closed() bool

Closed returns true if the server is already shutdown/closed

func (*Server) Logf

func (s *Server) Logf(f string, args ...any)

Logf logs to the default server logger if set

func (*Server) Run

func (s *Server) Run(ctx context.Context, addr string) error

Run starts the server on the specific address

func (*Server) RunAutoCert

func (s *Server) RunAutoCert(ctx context.Context, certCacheDir string, domains ...string) error

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) RunAutoCertDyn added in v1.1.0

func (s *Server) RunAutoCertDyn(ctx context.Context, opts *AutoCertOpts) error

RunAutoCertDyn enables automatic support for LetsEncrypt, using a dynamic HostPolicy. 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(ctx context.Context, certPairs []CertPair, opts *AutoCertOpts) 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

func (s *Server) SetKeepAlivesEnabled(v bool)

SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled.

func (*Server) Shutdown

func (s *Server) Shutdown(timeout time.Duration) error

Shutdown gracefully shutdown all the underlying http servers. You can optionally set a timeout.

func (*Server) Swagger

func (s *Server) Swagger() *router.Swagger

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL