Documentation ¶
Overview ¶
Package webfmwk implements an minimalist Go web framework
Example:
package main import ( w "github.com/burgesQ/webfmwk/v3" ) type Context struct { webfmwk.IContext content string } // Handler func hello(c w.IContext) error { return c.JSONOk("Hello, World!") } func main() { // Echo instance s := w.InitServer( webfmwk.EnableCheckIsUp() webfmwk.WithCORS(), webfmwk.WithLogger(log.GetLogger()), webfmwk.WithMiddlewars( middleware.Logging, middleware.Security), webfmwk.WithCustomContext(func(c *webfmwk.Context) webfmwk.IContext { return &Context{ Context: *c, content: "testing", } })) // Routes s.GET("/hello", hello) // start server on :4242 go func() { s.Start(":4242") }() // ctrl+c is handled internaly defer s.WaitAndStop() }
Learn more at https://github.com/burgesQ/webfmwk
Index ¶
- Constants
- Variables
- func AssignRequestID(ctx context.Context) context.Context
- func GetLogger() log.ILog
- func GetRequestID(ctx context.Context) string
- func Shutdown(ctx context.Context)
- type AnonymousError
- type Context
- func (c *Context) CheckHeader()
- func (c *Context) DecodeQP(dest interface{})
- func (c *Context) FetchContent(dest interface{})
- func (c *Context) GetContext() context.Context
- func (c *Context) GetQueries() map[string][]string
- func (c *Context) GetQuery(key string) (string, bool)
- func (c *Context) GetRequest() *http.Request
- func (c *Context) GetRequestID() string
- func (c *Context) GetVar(key string) string
- func (c *Context) IsPretty() bool
- func (c *Context) JSON(statusCode int, content interface{})
- func (c *Context) JSONAccepted(content interface{})
- func (c *Context) JSONBadRequest(content interface{})
- func (c *Context) JSONBlob(statusCode int, content []byte)
- func (c *Context) JSONConflict(content interface{})
- func (c *Context) JSONCreated(content interface{})
- func (c *Context) JSONInternalError(content interface{})
- func (c *Context) JSONNoContent()
- func (c *Context) JSONNotFound(content interface{})
- func (c *Context) JSONNotImplemented(content interface{})
- func (c *Context) JSONOk(content interface{})
- func (c *Context) JSONUnprocessable(content interface{})
- func (c *Context) OwnRecover()
- func (c *Context) SendResponse(statusCode int, content []byte, headers ...[2]string)
- func (c *Context) SetContext(ctx context.Context) IContext
- func (c *Context) SetLogger(logger log.ILog) IContext
- func (c *Context) SetQuery(q map[string][]string) IContext
- func (c *Context) SetRequest(r *http.Request) IContext
- func (c *Context) SetRequestID(id string) IContext
- func (c *Context) SetVars(v map[string]string) IContext
- func (c *Context) SetWriter(w http.ResponseWriter) IContext
- func (c *Context) Validate(dest interface{})
- type ContextKey
- type ErrorHandled
- func NewBadRequest(content interface{}) ErrorHandled
- func NewConflict(content interface{}) ErrorHandled
- func NewErrorHandled(op int, content interface{}) ErrorHandled
- func NewInternal(content interface{}) ErrorHandled
- func NewNoContent() ErrorHandled
- func NewNotAcceptable(content interface{}) ErrorHandled
- func NewNotFound(content interface{}) ErrorHandled
- func NewNotImplemented(content interface{}) ErrorHandled
- func NewProcessing(content interface{}) ErrorHandled
- func NewServiceUnavailable(content interface{}) ErrorHandled
- func NewUnauthorized(content interface{}) ErrorHandled
- func NewUnprocessable(content interface{}) ErrorHandled
- type HandlerSign
- type IContext
- type IErrorHandled
- type Option
- func CheckIsUp() Option
- func SetMaxHeaderBytes(val int) Option
- func SetPrefix(prefix string) Option
- func SetReadHeaderTimeout(val time.Duration) Option
- func SetReadTimeout(val time.Duration) Option
- func SetWriteTimeout(val time.Duration) Option
- func WithCORS() Option
- func WithCtrlC() Option
- func WithCustomContext(setter Setter) Option
- func WithDocHandler(handler http.Handler) Option
- func WithLogger(lg log.ILog) Option
- func WithMiddlewars(mw ...mux.MiddlewareFunc) Option
- type Route
- type Routes
- type RoutesPerPrefix
- type Server
- func (s *Server) AddRoute(r Route)
- func (s *Server) AddRoutes(r Routes)
- func (s *Server) DELETE(path string, handler HandlerSign)
- func (s *Server) DumpRoutes()
- func (s *Server) EnableCORS() *Server
- func (s *Server) EnableCheckIsUp() *Server
- func (s *Server) EnableCtrlC() *Server
- func (s *Server) GET(path string, handler HandlerSign)
- func (s *Server) GetContext() context.Context
- func (s *Server) GetLauncher() *WorkerLauncher
- func (s *Server) GetLogger() log.ILog
- func (s *Server) IsReady() chan bool
- func (s *Server) PATCH(path string, handler HandlerSign)
- func (s *Server) POST(path string, handler HandlerSign)
- func (s *Server) PUT(path string, handler HandlerSign)
- func (s *Server) RegisterDocHandler(handler http.Handler) *Server
- func (s *Server) RegisterLogger(lg log.ILog) *Server
- func (s *Server) RegisterMiddlewares(mw ...mux.MiddlewareFunc) *Server
- func (s *Server) RouteApplier(rpp RoutesPerPrefix)
- func (s *Server) SetCustomContext(setter Setter) *Server
- func (s *Server) SetPrefix(prefix string)
- func (s *Server) SetRouter() *mux.Router
- func (s *Server) Shutdown(ctx context.Context)
- func (s *Server) Start(addr string)
- func (s *Server) StartTLS(addr string, tlsStuffs TLSConfig)
- func (s *Server) WaitAndStop()
- type ServerMeta
- type Setter
- type TLSConfig
- type ValidationError
- type WorkerLauncher
Constants ¶
const ( GET = "GET" POST = "POST" PATCH = "PATCH" PUT = "PUT" DELETE = "DELETE" )
Variables ¶
var ( DefaultCurve = []tls.CurveID{ tls.CurveP256, tls.X25519, } DefaultCipher = []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384, tls.TLS_CHACHA20_POLY1305_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, } )
Functions ¶
func AssignRequestID ¶ added in v3.2.0
AssignRequestID will attach a brand new request ID to a http request
func GetRequestID ¶ added in v3.2.0
GetRequestID will get reqID from a http request and return it as a string
Types ¶
type AnonymousError ¶
type AnonymousError struct {
Error string `json:"error"`
}
AnonymousError struct is used to answer error
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context implement the IContext interface It hold the data used by the request
func (*Context) FetchContent ¶
func (c *Context) FetchContent(dest interface{})
FetchContent implement IContext It load payload in the dest interface{} using the system json library
func (*Context) GetContext ¶
GetContent implement IContext
func (*Context) GetQueries ¶
GetQueries implement IContext
func (*Context) GetRequest ¶ added in v3.2.4
GetRequest implement IContext
func (*Context) GetRequestID ¶ added in v3.2.0
SetRequest implement IContext
func (*Context) JSONAccepted ¶
func (c *Context) JSONAccepted(content interface{})
JSONOk implement IContext
func (*Context) JSONBadRequest ¶
func (c *Context) JSONBadRequest(content interface{})
JSONBadRequest implement IContext
func (*Context) JSONConflict ¶
func (c *Context) JSONConflict(content interface{})
JSONConflict implement IContext
func (*Context) JSONCreated ¶
func (c *Context) JSONCreated(content interface{})
JSONCreated implement IContext
func (*Context) JSONInternalError ¶
func (c *Context) JSONInternalError(content interface{})
JSONInternalError implement IContext
func (*Context) JSONNotFound ¶
func (c *Context) JSONNotFound(content interface{})
JSONNotFound implement IContext
func (*Context) JSONNotImplemented ¶
func (c *Context) JSONNotImplemented(content interface{})
JSONNotImplemented implement IContext
func (*Context) JSONUnprocessable ¶
func (c *Context) JSONUnprocessable(content interface{})
JSONUnprocessable implement IContext
func (*Context) SendResponse ¶
Send Response implement IContext
func (*Context) SetContext ¶
SetContext implement IContext
func (*Context) SetRequest ¶
SetRequest implement IContext
func (*Context) SetRequestID ¶ added in v3.2.0
SetRequest implement IContext
type ContextKey ¶ added in v3.2.0
type ContextKey string
ContextKey is used for context.Context value. The value requires a key that is not primitive type.
const ContextKeyRequestID ContextKey = "requestID"
ContextKeyRequestID is the ContextKey for RequestID
type ErrorHandled ¶
type ErrorHandled struct {
// contains filtered or unexported fields
}
ErrorHandled implement the IErrorHandled interface
func NewBadRequest ¶
func NewBadRequest(content interface{}) ErrorHandled
NewBadRequest produce an ErrorHandled with the status code 400
func NewConflict ¶
func NewConflict(content interface{}) ErrorHandled
NewConflict produce an ErrorHandled with the status code 409
func NewErrorHandled ¶
func NewErrorHandled(op int, content interface{}) ErrorHandled
NewError return a new ErrorHandled var
func NewInternal ¶
func NewInternal(content interface{}) ErrorHandled
NewUnprocessable produce an ErrorHandled with the status code 500
func NewNoContent ¶
func NewNoContent() ErrorHandled
NewNoContent produce an ErrorHandled with the status code 204
func NewNotAcceptable ¶
func NewNotAcceptable(content interface{}) ErrorHandled
NewNotAcceptable produce an ErrorHandled with the status code 406
func NewNotFound ¶
func NewNotFound(content interface{}) ErrorHandled
NewNotAcceptable produce an ErrorHandled with the status code 404
func NewNotImplemented ¶
func NewNotImplemented(content interface{}) ErrorHandled
NewUnprocessable produce an ErrorHandled with the status code 501
func NewProcessing ¶
func NewProcessing(content interface{}) ErrorHandled
NewProcessing produce an ErrorHandled with the status code 102
func NewServiceUnavailable ¶ added in v3.2.0
func NewServiceUnavailable(content interface{}) ErrorHandled
NewServiceUnavailable produce an ErrorHandled with the status code 422
func NewUnauthorized ¶
func NewUnauthorized(content interface{}) ErrorHandled
NewUnauthorized produce an ErrorHandled with the status code 401
func NewUnprocessable ¶
func NewUnprocessable(content interface{}) ErrorHandled
NewUnprocessable produce an ErrorHandled with the status code 422
func (ErrorHandled) Error ¶
func (e ErrorHandled) Error() string
Error implement the error interface
func (ErrorHandled) GetContent ¶
func (e ErrorHandled) GetContent() interface{}
GetContent implement the IErrorHandled interface
func (ErrorHandled) GetOPCode ¶
func (e ErrorHandled) GetOPCode() int
GetOPCode implement the IErrorHandled interface
func (ErrorHandled) SetWrapped ¶
func (e ErrorHandled) SetWrapped(err error) IErrorHandled
func (ErrorHandled) Unwrap ¶
func (e ErrorHandled) Unwrap() error
type HandlerSign ¶
type HandlerSign func(c IContext)
HandlerSign hold the signature of the controller
type IContext ¶
type IContext interface { GetRequestID() string SetRequestID(id string) IContext // GetRequest return the holded http.Request object GetRequest() *http.Request // SetRequest is used to save the request object SetRequest(rq *http.Request) IContext // SetWriter is used to save the ResponseWriter obj SetWriter(rw http.ResponseWriter) IContext // SetVars is used to save the url vars SetVars(vars map[string]string) IContext // GetVar return the url var parameters. Empty string for none GetVar(key string) (val string) // SetQuery save the query param object SetQuery(query map[string][]string) IContext // GetQueries return the queries object GetQueries() map[string][]string // GetQuery fetch the query object key GetQuery(key string) (val string, ok bool) // SetLogger set the logger of the ctx SetLogger(logger log.ILog) IContext // Save the given context object into the fmwk context SetContext(ctx context.Context) IContext // Fetch the previously saved context object GetContext() context.Context // FetchContent extract the content from the body FetchContent(content interface{}) // Validate is used to validate a content of the content params Validate(content interface{}) // Decode load the query param in the content object DecodeQP(content interface{}) // IsPretty toggle the compact outptu mode IsPretty() bool // CheckHeader ensure the Content-Type of the request CheckHeader() // OwnRecover is used to encapsulate the wanted panic OwnRecover() // SendResponse create & send a response according to the parameters SendResponse(op int, content []byte, headers ...[2]string) // JSONBlob answer the JSON content with the status code op JSONBlob(op int, content []byte) // JSON answer the JSON content with the status code op JSON(op int, content interface{}) // 200 JSONOk(interface{}) // 201 JSONCreated(interface{}) // 202 JSONAccepted(interface{}) // JSONNotImplemented(interface{}) // JSONNoContent() // JSONBadRequest(interface{}) // JSONUnprocessable(interface{}) // 404 JSONNotFound(interface{}) // JSONConflict(interface{}) // 500 JSONInternalError(interface{}) }
IContext Interface implement the context used in this project
type IErrorHandled ¶
type IErrorHandled interface { // error Error() string Unwrap() error GetOPCode() int GetContent() interface{} SetWrapped(err error) IErrorHandled }
IErrorHandled interface implement the panic recovering
type Option ¶ added in v3.2.0
type Option func(s *Server)
Option is tu be used this way :
s := w.InitServer( webfmwk.EnableCheckIsUp() webfmwk.WithCORS(), webfmwk.WithLogger(log.GetLogger()), webfmwk.WithMiddlewars( middleware.Logging, middleware.Security))
func SetMaxHeaderBytes ¶ added in v3.2.0
func SetReadHeaderTimeout ¶ added in v3.2.0
func SetReadTimeout ¶ added in v3.2.0
ReadTimeout is a timing constraint on the client http request imposed by the server from the moment of initial connection up to the time the entire request body has been read.
[Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]
func SetWriteTimeout ¶ added in v3.2.0
WriteTimeout is a time limit imposed on client connecting to the server via http from the time the server has completed reading the request header up to the time it has finished writing the response.
[Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]
func WithCustomContext ¶ added in v3.2.0
func WithDocHandler ¶ added in v3.2.0
func WithLogger ¶ added in v3.2.0
func WithMiddlewars ¶ added in v3.2.0
func WithMiddlewars(mw ...mux.MiddlewareFunc) Option
type Route ¶
type Route struct { Verbe string `json:"verbe"` Path string `json:"path"` Name string `json:"name"` Handler HandlerSign `json:"-"` }
Route hold the data for one route
type RoutesPerPrefix ¶
RoutesPerPrefix hold the routes and there respectiv prefix
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a struct holding all the necessary data / struct
func InitServer ¶
func (*Server) DELETE ¶
func (s *Server) DELETE(path string, handler HandlerSign)
DELETE expose a route to the http verb DELETE
func (*Server) DumpRoutes ¶ added in v3.2.0
func (s *Server) DumpRoutes()
DumpRoutes dump the API endpoints using the server logger
func (*Server) EnableCORS ¶ added in v3.2.0
EnableCORS enable CORS verification
func (*Server) EnableCheckIsUp ¶ added in v3.2.0
EnableCheckIsUp add an /ping endpoint. Is used, cnce a server is started, the user can check weather the server is up or not by reading the isReady channel vie the IsReady() method
func (*Server) EnableCtrlC ¶ added in v3.2.0
EnableCtrlC let the server handle the SIGINT interuption. To add worker to the interuption pool, please use the `GetLauncher` method
func (*Server) GET ¶
func (s *Server) GET(path string, handler HandlerSign)
GET expose a route to the http verb GET
func (*Server) GetContext ¶
GetContext return the context.Context used
func (*Server) GetLauncher ¶
func (s *Server) GetLauncher() *WorkerLauncher
GetLauncher return a pointer to the internal workerLauncher
func (*Server) IsReady ¶ added in v3.2.0
IsReady return the channel on which `true` is send once the server is up
func (*Server) PATCH ¶
func (s *Server) PATCH(path string, handler HandlerSign)
PATCH expose a route to the http verb PATCH
func (*Server) POST ¶
func (s *Server) POST(path string, handler HandlerSign)
POST expose a route to the http verb POST
func (*Server) PUT ¶
func (s *Server) PUT(path string, handler HandlerSign)
PUT expose a route to the http verb PUT
func (*Server) RegisterDocHandler ¶
RegisterDocHandler is used to register an swagger doc handler
func (*Server) RegisterLogger ¶ added in v3.2.0
RegisterLogger register the ILog used
func (*Server) RegisterMiddlewares ¶ added in v3.2.0
func (s *Server) RegisterMiddlewares(mw ...mux.MiddlewareFunc) *Server
RegisterMiddlewares register the middlewares arguments
func (*Server) RouteApplier ¶
func (s *Server) RouteApplier(rpp RoutesPerPrefix)
RouteApplier apply the array of RoutePerPrefix
func (*Server) SetCustomContext ¶
SetCustomContext save a custom context so it can be fetched in the controllers
func (*Server) SetRouter ¶
SetRouter create a mux.Handler router and then : register the middle wares, register the user defined routes per prefix, and return the routes handler
func (*Server) WaitAndStop ¶
func (s *Server) WaitAndStop()
WaitAndStop wait for all servers to terminate. Use of a sync.waitGroup to properly wait all running servers.
type ServerMeta ¶ added in v3.2.0
type ServerMeta struct {
// contains filtered or unexported fields
}
type TLSConfig ¶
type TLSConfig struct { Cert string `json:"cert"` Key string `json:"key"` Insecure bool `json:"insecure"` }
TLSConfig contain the tls config passed by the config file
type ValidationError ¶
type ValidationError struct {
Error validator.ValidationErrorsTranslations `json:"error"`
}
Context implement the IContext interface It hold the data used by the request
type WorkerLauncher ¶
type WorkerLauncher struct {
// contains filtered or unexported fields
}
WorkerLauncher hold the different workers
func CreateWorkerLauncher ¶
func CreateWorkerLauncher(wg *sync.WaitGroup, cancel context.CancelFunc) WorkerLauncher
to use as a factory as the fields are unexported
func (*WorkerLauncher) Start ¶
func (l *WorkerLauncher) Start(name string, fn func() error)
launch a worker who will be wait & kill at the same time than the others
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
package log implement the ILog interface used by the webfmwk
|
package log implement the ILog interface used by the webfmwk |
Package middleware implement some basic middleware for the webfmwk middleware provides a convenient mechanism for filtering HTTP requests entering the application.
|
Package middleware implement some basic middleware for the webfmwk middleware provides a convenient mechanism for filtering HTTP requests entering the application. |
Package testing hold some testing method used for both assertion and testing the webfmwk
|
Package testing hold some testing method used for both assertion and testing the webfmwk |