Documentation ¶
Index ¶
- func Prefix(path string) string
- func WatchAPIs(request RequestContext, status Status)
- type API
- type APIListener
- type Controller
- func (controller *Controller) AddAPIListeners(listeners ...APIListener)
- func (controller *Controller) AddRequestListeners(listeners ...RequestListener)
- func (controller *Controller) AddResponseListener(listeners ...ResponseListener)
- func (controller *Controller) AddRoutes(routes ...Route)
- func (controller *Controller) RegisterInterrupts(interrupts ...Interrupt)
- func (controller *Controller) SetTimeout(timeout time.Duration)
- type CorsHandler
- type ErrorHandler
- type Interrupt
- type MalformedRequestContext
- type Params
- type ParseError
- type PathParams
- func (pp PathParams) Get(key string) (string, bool)
- func (pp PathParams) GetFloat(key string) (float64, error)
- func (pp PathParams) GetInt(key string) (int, error)
- func (pp PathParams) MustGet(key string) string
- func (pp PathParams) MustGetFloat(key string) float64
- func (pp PathParams) MustGetInt(key string) int
- type Push
- type Queries
- func (q Queries) Get(key string) ([]string, bool)
- func (q Queries) GetFloat(key string) (float64, error)
- func (q Queries) GetInt(key string) (int, error)
- func (q Queries) GetOne(key string) (string, bool)
- func (q Queries) MustGet(key string) string
- func (q Queries) MustGetFloat(key string) float64
- func (q Queries) MustGetInt(key string) int
- type RequestBody
- type RequestContext
- func (request RequestContext) AddCookie(cookie *http.Cookie)
- func (request RequestContext) Cookie(name string) (*http.Cookie, error)
- func (request RequestContext) Cookies() []*http.Cookie
- func (request RequestContext) Form() (map[string][]string, error)
- func (request RequestContext) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (request RequestContext) FormValue(key string) string
- func (request RequestContext) ParseMultipartForm(maxMemory int64) error
- func (request RequestContext) PostForm() (map[string][]string, error)
- func (request RequestContext) PostFormValue(key string) string
- func (request RequestContext) QueryToObj(a any) error
- func (request RequestContext) ReceivedAt() time.Time
- func (request RequestContext) Referer() string
- func (request RequestContext) UserAgent() string
- type RequestListener
- type ResponseEntity
- type ResponseListener
- type Route
- func DELETE(pattern string, api API) Route
- func GET(pattern string, api API) Route
- func Handle(method string, pattern string, api API) Route
- func OPTIONS(pattern string, api API) Route
- func PATCH(pattern string, api API) Route
- func POST(pattern string, api API) Route
- func PUT(pattern string, api API) Route
- func StaticDir(pattern string, dir string) Route
- type RouteCreationStage
- type Server
- func (server *Server) AddAPIListeners(listeners ...APIListener)
- func (server *Server) AddRequestListeners(listeners ...RequestListener)
- func (server *Server) AddResponseListeners(listeners ...ResponseListener)
- func (server *Server) AddRoutes(routes ...Route)
- func (server *Server) CorsHandler(handler CorsHandler)
- func (server *Server) NotFoundAction(action API)
- func (server *Server) Register(controllers ...*Controller)
- func (server *Server) RegisterInterrupts(interrupts ...Interrupt)
- func (server *Server) SetErrorHandler(action ErrorHandler)
- func (server *Server) SetTimeout(dur time.Duration)
- func (server *Server) Start() error
- type Status
- func BadRequest(body ResponseEntity) Status
- func CreateResponse(statusCode int, body ResponseEntity) Status
- func Created(body ResponseEntity) Status
- func File(path string) Status
- func Forbidden(body ResponseEntity) Status
- func Found(location string) Status
- func InternalServerError(body ResponseEntity) Status
- func MethodNotAllowed(body ResponseEntity) Status
- func MovedPermanently(location string) Status
- func NotFound(body ResponseEntity) Status
- func Ok(body ResponseEntity) Status
- func PermanentRedirect(location string) Status
- func Unauthorized(body ResponseEntity) Status
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Prefix ¶ added in v0.4.6
Prefix can be used as a pattern inside route definition, which matches all the requests that contain the given prefix. Note that this is appended to the corresponding controller's prefix in which the route is defined.
func WatchAPIs ¶
func WatchAPIs(request RequestContext, status Status)
WatchAPIs is the default request and response logger for stgin. It logs the input request and the output response into the console.
Types ¶
type API ¶
type API = func(c RequestContext) Status
API is the lowest-level functionality in stgin. It represents a function which takes a request, and generates an HTTP response.
type APIListener ¶ added in v0.2.3
type APIListener = func(RequestContext, Status)
APIListener is a function which is applied to both request and response, after the response is written to the client. It can be defined both on the controller layer, or server layer.
type Controller ¶
type Controller struct { Name string // contains filtered or unexported fields }
Controller is a struct which groups some routes, and may have a path prefix. And might hold some request/response/api listeners.
func NewController ¶
func NewController(name string, prefix string) *Controller
NewController returns a pointer to a newly created controller with the given name and path prefixes.
func (*Controller) AddAPIListeners ¶ added in v0.2.3
func (controller *Controller) AddAPIListeners(listeners ...APIListener)
AddAPIListeners registers the given listeners to the controller. These listeners then will be applied to all the incoming/outgoing requests and responses after they're evaluated And returned to the client.
func (*Controller) AddRequestListeners ¶
func (controller *Controller) AddRequestListeners(listeners ...RequestListener)
AddRequestListeners registers the given listeners to the controller. These listeners then will be applied to all the requests coming inside this controller.
func (*Controller) AddResponseListener ¶
func (controller *Controller) AddResponseListener(listeners ...ResponseListener)
AddResponseListener registers the given listeners to the controller. These listeners then will be applied to all the outgoing responses from this controller.
func (*Controller) AddRoutes ¶
func (controller *Controller) AddRoutes(routes ...Route)
AddRoutes normalizes, and evaluates path patterns for the given routes, and then adds them to the routes it contains.
func (*Controller) RegisterInterrupts ¶ added in v0.6.3
func (controller *Controller) RegisterInterrupts(interrupts ...Interrupt)
RegisterInterrupts adds the given interrupts to the controller's already existing interrupts.
func (*Controller) SetTimeout ¶ added in v0.6.3
func (controller *Controller) SetTimeout(timeout time.Duration)
SetTimeout registers a timeout interrupt into the controller.
type CorsHandler ¶ added in v0.5.4
type CorsHandler struct { AllowOrigin []string AllowCredentials []string AllowHeaders []string AllowMethods []string }
CorsHandler is just a semantic wrapper over common CORS headers.
type ErrorHandler ¶ added in v0.2.4
type ErrorHandler = func(request RequestContext, err any) Status
ErrorHandler is a function which can decide what to do, based on the request and the error.
type Interrupt ¶ added in v0.6.3
type Interrupt interface {
TriggerFor(request RequestContext, completeWith chan *Status)
}
Interrupt is n abstract semantic, that can be executed along-side the request, And if some event happens, can abort the request and complete with another response, which is filled within completeWith. A real world example would be timeouts; server.SetTimeout actually uses an interrupt to perform timeout operations.
func TimeoutInterrupt ¶ added in v0.6.3
type MalformedRequestContext ¶ added in v0.2.5
type MalformedRequestContext struct {
// contains filtered or unexported fields
}
func (MalformedRequestContext) Error ¶ added in v0.2.5
func (mrc MalformedRequestContext) Error() string
type ParseError ¶ added in v0.2.5
type ParseError struct {
// contains filtered or unexported fields
}
func (ParseError) Error ¶ added in v0.2.5
func (ije ParseError) Error() string
type PathParams ¶ added in v0.5.9
PathParams is a struct wrapped around the path parameters of an HTTP request. It provides some receiver functions which make it easier than ever to use them.
func (PathParams) Get ¶ added in v0.5.9
func (pp PathParams) Get(key string) (string, bool)
Get tries to find a path parameter by the given key.
func (PathParams) GetFloat ¶ added in v0.5.9
func (pp PathParams) GetFloat(key string) (float64, error)
GetFloat tries to find a path parameter by the given key, and tries to convert it to float. In case any error happens from finding to converting, this function returns immediately.
func (PathParams) GetInt ¶ added in v0.5.9
func (pp PathParams) GetInt(key string) (int, error)
GetInt tries to find a path parameter by the given key, and tries to convert it to integer. In case any error happens from finding to converting, this function returns immediately.
func (PathParams) MustGet ¶ added in v0.5.9
func (pp PathParams) MustGet(key string) string
MustGet tries to find a path parameter by the given key. Returns empty string in case it couldn't be found.
func (PathParams) MustGetFloat ¶ added in v0.5.9
func (pp PathParams) MustGetFloat(key string) float64
MustGetFloat tries to find a path parameter by the given key, and tries to convert it to float. This function should be used when you have defined your path parameter to be floating point inside the route pattern (like "/geo/$lat:float"). This function will panic in case of any error.
func (PathParams) MustGetInt ¶ added in v0.5.9
func (pp PathParams) MustGetInt(key string) int
MustGetInt tries to find a path parameter by the given key, and tries to convert it to integer. This function should be used when you have defined your path parameter to be integer inside the route pattern (like "/users/$id:int"). This function will panic in case of any error.
type Push ¶ added in v0.4.5
type Push struct { IsSupported bool // contains filtered or unexported fields }
Push is a struct that represents both the ability, and the functionality of http push inside this request.
type Queries ¶ added in v0.5.9
Queries is just a struct holding all the key value pairs of request's query parameters. It also defines some useful receiver functions in order to ease fetching query params.
func (Queries) Get ¶ added in v0.5.9
Get looks for the given key in all queries, and returns the value if it exists.
func (Queries) GetFloat ¶ added in v0.5.9
GetFloat is the same as Get, but when you have defined query type to be floating point inside the route pattern. In case of any error from finding to converting, the error is returned immediately.
func (Queries) GetInt ¶ added in v0.5.9
GetInt is the same as Get, but when you have defined query type to be integer inside the route pattern. In case of any error from finding to converting, the error is returned immediately.
func (Queries) GetOne ¶ added in v0.5.9
GetOne is used when you're sure if one and only one value exists for the given query.
func (Queries) MustGet ¶ added in v0.5.9
MustGet can be used when you're sure about the existence of a key in query parameters. It panics in it has 0 or more than 1 values.
func (Queries) MustGetFloat ¶ added in v0.5.9
MustGetFloat is the same as MustGet, but when you have defined query type to be floating point inside the route pattern. It panics in case of any error from finding to converting the value to float.
func (Queries) MustGetInt ¶ added in v0.5.9
MustGetInt is the same as MustGet, but when you have defined query type to be integer inside the route pattern. It panics in case of any error from finding to converting the value to int.
type RequestBody ¶
type RequestBody struct {
// contains filtered or unexported fields
}
RequestBody holds the bytes of the request's body entity.
func (*RequestBody) JSONInto ¶ added in v0.2.5
func (body *RequestBody) JSONInto(a any)
JSONInto receives a pointer to anything, and will try to parse the request's JSON entity into it. It panics in case any error happens.
func (*RequestBody) SafeJSONInto ¶ added in v0.2.5
func (body *RequestBody) SafeJSONInto(a any) error
SafeJSONInto receives a pointer to anything, and will try to parse the request bytes into it as JSON. if any error occurs, it is returned immediately by the function.
func (*RequestBody) SafeXMLInto ¶ added in v0.2.5
func (body *RequestBody) SafeXMLInto(a any) error
SafeXMLInto receives a pointer to anything, and will try to parse the request bytes into it as JSON. if any error occurs, it is returned immediately by the function.
func (*RequestBody) XMLInto ¶ added in v0.2.5
func (body *RequestBody) XMLInto(a any)
XMLInto receives a pointer to anything, and will try to parse the request's XML entity into it. It panics in case any error happens.
type RequestContext ¶
type RequestContext struct { Url string QueryParams Queries PathParams PathParams Headers http.Header Trailer http.Header Body func() *RequestBody Method string ContentLength int64 Host string MultipartForm func() *multipart.Form Scheme string RemoteAddr string Underlying *http.Request HttpPush Push // contains filtered or unexported fields }
RequestContext holds all the information about incoming http requests.
func (RequestContext) AddCookie ¶ added in v0.4.1
func (request RequestContext) AddCookie(cookie *http.Cookie)
AddCookie adds the cookie to the request.
func (RequestContext) Cookie ¶ added in v0.4.1
func (request RequestContext) Cookie(name string) (*http.Cookie, error)
Cookie tries to find a cookie with the given name.
func (RequestContext) Cookies ¶ added in v0.4.1
func (request RequestContext) Cookies() []*http.Cookie
Cookies returns the cookies that are attached to the request.
func (RequestContext) Form ¶ added in v0.5.5
func (request RequestContext) Form() (map[string][]string, error)
Form returns all the key-values inside the given request. It calls ParseForm itself.
func (RequestContext) FormFile ¶ added in v0.5.5
func (request RequestContext) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
FormFile is a shortcut to get a file with the given name from multipart form.
func (RequestContext) FormValue ¶ added in v0.5.5
func (request RequestContext) FormValue(key string) string
FormValue is a shortcut to get a value by name inside the request form instead of parsing the whole form.
func (RequestContext) ParseMultipartForm ¶ added in v0.5.5
func (request RequestContext) ParseMultipartForm(maxMemory int64) error
ParseMultipartForm is the manual approach to parse the request's entity to multipart form. Please read (*http.Request).ParseMultipartForm for more detailed information.
func (RequestContext) PostForm ¶ added in v0.5.5
func (request RequestContext) PostForm() (map[string][]string, error)
PostForm returns all the key-values inside the given request's post-form.
func (RequestContext) PostFormValue ¶ added in v0.5.5
func (request RequestContext) PostFormValue(key string) string
PostFormValue can get a value by the given name from request post-form.
func (RequestContext) QueryToObj ¶ added in v0.5.4
func (request RequestContext) QueryToObj(a any) error
QueryToObj receives a pointer to a struct, and tries to parse the query params into it. Please read the documentations [here](https://github.com/AminMal/stgin#query-parameters) for more details.
func (RequestContext) ReceivedAt ¶ added in v0.6.2
func (request RequestContext) ReceivedAt() time.Time
func (RequestContext) Referer ¶ added in v0.5.5
func (request RequestContext) Referer() string
Referer returns the value of referer header in http request, returns empty string if it does not exist.
func (RequestContext) UserAgent ¶ added in v0.5.5
func (request RequestContext) UserAgent() string
UserAgent returns the value of request's user agent, returns empty string if it does not exist.
type RequestListener ¶
type RequestListener = func(RequestContext) RequestContext
RequestListener is a function which is applied to the incoming requests, before the api actually receives it. It can be defined both on the controller layer, or server layer.
type ResponseEntity ¶ added in v0.4.1
type ResponseEntity interface { // ContentType represents *HTTP* response content type of the entity. ContentType() string // Bytes function is responsible to provide response entity bytes, and eny error if exists. Bytes() ([]byte, error) }
ResponseEntity is an interface representing anything that can be sent through http response body. Structs implementing ResponseEntity must have a content type (which is written directly in the response), And also a function which can provide entity bytes, or any error if exists. So for instance if you wanted to define a custom PDF ResponseEntity (which is already supported using File function), type PDF struct { filepath string } func (pdf PDF) ContentType() string { return "application/pdf" } func (pdf PDF) Bytes() ([]byte, error) { ... read file ... } And simply use it inside your APIs. return stgin.Ok(PDF{filePath})
func Empty ¶ added in v0.5.4
func Empty() ResponseEntity
Empty is used when you want to return empty responses to the client. There are situations where status codes talk, and there is no need to populate response body with non-meaningful data.
func Json ¶ added in v0.4.1
func Json(a any) ResponseEntity
Json is a shortcut to convert any object into a JSON ResponseEntity.
func Text ¶ added in v0.4.1
func Text(text string) ResponseEntity
Text is a shortcut to convert any object into a text ResponseEntity.
func Xml ¶ added in v0.4.1
func Xml(a any) ResponseEntity
Xml is a shortcut to convert any object into an XML ResponseEntity.
type ResponseListener ¶
ResponseListener is a function which is applied to the outgoing http responses, after they're evaluated by the api. It can be defined both on the controller layer, or server layer.
type Route ¶
type Route struct { Path string Method string Action API // contains filtered or unexported fields }
Route is a struct which specifies whether a request should be handled by the given Action inside the route.
func Handle ¶ added in v0.4.4
Handle is a generic function that can be used for other http methods that do not have a helper function in stgin (like GET).
type RouteCreationStage ¶
type RouteCreationStage struct {
// contains filtered or unexported fields
}
RouteCreationStage is a struct that can make routes step by step. Is only returned after OnPath function is called.
func OnPath ¶
func OnPath(path string) RouteCreationStage
OnPath is the starting point of route creation stage, specifies the pattern.
func (RouteCreationStage) Do ¶
func (stage RouteCreationStage) Do(api API) Route
Do assign's the api action to the route creation stage, and returns the resulting route.
func (RouteCreationStage) WithMethod ¶
func (stage RouteCreationStage) WithMethod(method string) RouteCreationStage
WithMethod attaches the method to the route creation stage.
type Server ¶
type Server struct { Controllers []*Controller // contains filtered or unexported fields }
Server is the starting point of stgin applications, which holds the address, controllers, APIs and server-level listeners. Which can be run on the specified address.
func DefaultServer ¶ added in v0.4.1
DefaultServer is the recommended approach to get a new Server. It includes error handler and api logger by default.
func (*Server) AddAPIListeners ¶ added in v0.2.3
func (server *Server) AddAPIListeners(listeners ...APIListener)
AddAPIListeners adds the given api listeners to server-level listeners (which then will be applied to all the incoming requests and outgoing responses after they're finished).
func (*Server) AddRequestListeners ¶
func (server *Server) AddRequestListeners(listeners ...RequestListener)
AddRequestListeners adds the given request listeners to server-level listeners (which then will be applied to all the incoming requests).
func (*Server) AddResponseListeners ¶
func (server *Server) AddResponseListeners(listeners ...ResponseListener)
AddResponseListeners adds the given response listeners to server-level listeners (which then will be applied to all the outgoing responses).
func (*Server) AddRoutes ¶ added in v0.5.2
AddRoutes is an alternative to controller.AddRoutes, which adds the given routes to the server's default controller.
func (*Server) CorsHandler ¶ added in v0.5.4
func (server *Server) CorsHandler(handler CorsHandler)
CorsHandler function takes the responsibility to handle requests with "OPTIONS" method with the given headers in handler parameter.
func (*Server) NotFoundAction ¶ added in v0.2.2
NotFoundAction defines what server should do with the requests that match no routes.
func (*Server) Register ¶
func (server *Server) Register(controllers ...*Controller)
Register appends given controllers to the server.
func (*Server) RegisterInterrupts ¶ added in v0.6.3
RegisterInterrupts adds the given interrupts to the server's already existing interrupts
func (*Server) SetErrorHandler ¶ added in v0.2.5
func (server *Server) SetErrorHandler(action ErrorHandler)
SetErrorHandler defines what server should do in case some api panics.
func (*Server) SetTimeout ¶ added in v0.6.1
SetTimeout registers a timeout interrupt to the server
type Status ¶
type Status struct { StatusCode int Entity ResponseEntity Headers http.Header // contains filtered or unexported fields }
Status is the return type of stgin APIs. It represents an HTTP response with a status code, headers, body and cookies.
func BadRequest ¶
func BadRequest(body ResponseEntity) Status
BadRequest represents a basic http 400 response with the given body.
func CreateResponse ¶
func CreateResponse(statusCode int, body ResponseEntity) Status
CreateResponse can be used in order to make responses that are not available in default functions in stgin. For instance a 202 http response.
func Created ¶
func Created(body ResponseEntity) Status
Created represents a basic http 201 response with the given body.
func File ¶ added in v0.4.5
File is used to return a file itself as an HTTP response. If the file is not found, it returns 404 not found to the client. If there are issues reading file or anything else related, 500 internal server error is returned to the client.
func Forbidden ¶
func Forbidden(body ResponseEntity) Status
Forbidden represents a basic http 403 response with the given body.
func InternalServerError ¶
func InternalServerError(body ResponseEntity) Status
InternalServerError represents a basic http 500 response with the given body.
func MethodNotAllowed ¶ added in v0.2.2
func MethodNotAllowed(body ResponseEntity) Status
MethodNotAllowed represents a basic http 405 response with the given body.
func MovedPermanently ¶
MovedPermanently represents a basic http 301 redirect to the given location.
func NotFound ¶
func NotFound(body ResponseEntity) Status
NotFound represents a basic http 404 response with the given body.
func Ok ¶
func Ok(body ResponseEntity) Status
Ok represents a basic http 200 response with the given body.
func PermanentRedirect ¶
PermanentRedirect represents a basic http 308 redirect to the given location.
func Unauthorized ¶
func Unauthorized(body ResponseEntity) Status
Unauthorized represents a basic http 401 response with the given body.
func (Status) WithCookies ¶ added in v0.4.1
WithCookies returns a new Status, appended the given cookies.