Documentation
¶
Index ¶
- func AuthenticatedHandlerFunc[RequestBody any, Params any, AuthModel any](h AuthenticatedHandler[RequestBody, Params, AuthModel]) http.Handler
- func HandleError(w http.ResponseWriter, r *http.Request, err error)
- func HandlerFunc[RequestBody any, Params any](h Handler[RequestBody, Params]) http.Handler
- type Application
- type AuthFunc
- type AuthenticatedHandler
- type ErrorResponse
- type HTTPError
- type Handler
- type NoBody
- type NoParams
- type ParameterType
- type Request
- type Response
- type Router
- func (r *Router) DELETE(path string, handler http.Handler)
- func (r *Router) Extend(middleware alice.Chain)
- func (r *Router) GET(path string, handler http.Handler)
- func (r *Router) HEAD(path string, handler http.Handler)
- func (r *Router) OPTIONS(path string, handler http.Handler)
- func (r *Router) PATCH(path string, handler http.Handler)
- func (r *Router) POST(path string, handler http.Handler)
- func (r *Router) PUT(path string, handler http.Handler)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Use(middleware func(next http.Handler) http.Handler)
- type Settings
- type ValidationError
- type ValidationErrors
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthenticatedHandlerFunc ¶
func AuthenticatedHandlerFunc[RequestBody any, Params any, AuthModel any](h AuthenticatedHandler[RequestBody, Params, AuthModel]) http.Handler
AuthenticatedHandlerFunc returns an http.Handler that can be used for authenticated routes
func HandleError ¶ added in v0.1.1
func HandleError(w http.ResponseWriter, r *http.Request, err error)
HandleError is a helper function for handling errors in HTTP handlers
func HandlerFunc ¶
HandlerFunc returns an http.Handler that can be used for non-authenticated routes
Types ¶
type Application ¶
type Application[AuthModel any] struct { // Router is the main router for the application Router *Router // contains filtered or unexported fields }
Application is the main application struct that holds the router and other application settings
func Default ¶
func Default() *Application[struct{}]
Default returns a new Application application with default settings
func DefaultWithAuth ¶
func DefaultWithAuth[AuthModel any](authFunc AuthFunc[AuthModel]) *Application[AuthModel]
DefaultWithAuth returns a new Application application with default settings and ability to have authenticated routes using the provided authFunc to authenticate and retrieve the user
func New ¶
func New(settings ...Settings) *Application[struct{}]
New returns a new Application application
func NewWithAuth ¶
func NewWithAuth[User any](authFunc AuthFunc[User], st ...Settings) *Application[User]
NewWithAuth returns a new Application application with ability to have authenticated routes using the provided AuthFunc to authenticate and retrieve the authenticated model
func (*Application[AuthModel]) ServeHTTP ¶ added in v0.2.0
func (s *Application[AuthModel]) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements the http.Handler interface for the Simba Application
type AuthFunc ¶
AuthFunc is a function type for authenticating and retrieving an authenticated model struct from a request
type AuthenticatedHandler ¶
type AuthenticatedHandler[RequestBody any, Params any, AuthModel any] func(ctx context.Context, req *Request[RequestBody, Params], user *AuthModel) (*Response, error)
AuthenticatedHandler handles a request with the request body and params.
Example usage:
Define a request body struct:
type RequestBody struct {
Test string `json:"test" validate:"required"`
}
Define a request params struct:
type Params struct {
Name string `header:"name" validate:"required"`
ID int `path:"id" validate:"required"`
Active bool `query:"active" validate:"required"`
Page int64 `query:"page" validate:"min=0"`
Size int64 `query:"size" validate:"min=0"`
}
Define a user struct:
type AuthModel struct {
ID int
Name string
Role string
}
Define a handler function:
func(ctx context.Context, req *simba.Request[RequestBody, Params], user *AuthModel) (*simba.Response, error) {
// Access the request body and params fields
req.Body.Test
req.Params.Name
req.Params.ID
req.Params.Page
req.Params.Size
// Access the user fields
user.ID
user.Name
user.Role
// Return a response
return &simba.Response{
Headers: map[string][]string{"My-Header": {"header-value"}},
Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "cookie-value"}},
Body: map[string]string{"message": "success"},
Status: http.StatusOK,
}, nil
}
Register the handler:
router.POST("/test/:id", simba.AuthenticatedHandlerFunc(handler))
func (AuthenticatedHandler[RequestBody, Params, AuthModel]) ServeHTTP ¶
func (h AuthenticatedHandler[RequestBody, Params, AuthModel]) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for AuthenticatedHandler
type ErrorResponse ¶
type ErrorResponse struct {
// Timestamp of the error
Timestamp time.Time `json:"timestamp"`
// HTTP status code
Status int `json:"status"`
// HTTP error type
Error string `json:"error"`
// Path of the request
Path string `json:"path"`
// Method of the request
Method string `json:"method"`
// Request ID
RequestID string `json:"requestId,omitempty"`
// Error message
Message string `json:"message,omitempty"`
// Validation errors
ValidationErrors []ValidationError `json:"validationErrors,omitempty"`
} // @Name ErrorResponse
ErrorResponse defines the structure of an error message @Description Represents the structure of an error message returned by the API
func NewErrorResponse ¶
func NewErrorResponse(r *http.Request, status int, message string, validationErrors ...ValidationError) *ErrorResponse
NewErrorResponse creates a new ErrorResponse instance with the given status and message
type HTTPError ¶
type HTTPError struct {
HttpStatusCode int
Message string
ValidationErrors ValidationErrors
// contains filtered or unexported fields
}
func NewHttpError ¶
func NewHttpError(httpStatusCode int, publicMessage string, err error, validationErrors ...ValidationError) *HTTPError
NewHttpError creates a new ApiError
func WrapErrorHTTP ¶
WrapErrorHTTP wraps an error with an HTTP status code
func (*HTTPError) HasValidationErrors ¶
HasValidationErrors checks if there are validation errors
type Handler ¶
type Handler[RequestBody any, Params any] func(ctx context.Context, req *Request[RequestBody, Params]) (*Response, error)
Handler handles a request with the request body and params.
Example usage:
Define a request body struct:
type RequestBody struct {
Test string `json:"test" validate:"required"`
}
Define a request params struct:
type Params struct {
Name string `header:"name" validate:"required"`
ID int `path:"id" validate:"required"`
Active bool `query:"active" validate:"required"`
Page int64 `query:"page" validate:"min=0"`
Size int64 `query:"size" validate:"min=0"`
}
Define a handler function:
func(ctx context.Context, req *simba.Request[RequestBody, Params]) (*simba.Response, error) {
// Access the request body and params fields
req.Body.Test
req.Params.Name
req.Params.ID
req.Params.Page
req.Params.Size
// Return a response
return &simba.Response{
Headers: map[string][]string{"My-Header": {"header-value"}},
Cookies: []*http.Cookie{{Name: "My-Cookie", Value: "cookie-value"}},
Body: map[string]string{"message": "success"},
Status: http.StatusOK,
}, nil
}
Register the handler:
router.POST("/test/:id", simba.HandlerFunc(handler))
type ParameterType ¶
type ParameterType string
const ( ParameterTypeHeader ParameterType = "header" ParameterTypePath ParameterType = "path" ParameterTypeQuery ParameterType = "query" ParameterTypeBody ParameterType = "body" )
type Request ¶
type Request[RequestBody any, RequestParams any] struct { Cookies []*http.Cookie Body RequestBody Params RequestParams }
Request represents a HTTP request
type Router ¶ added in v0.2.0
type Router struct {
// contains filtered or unexported fields
}
Router is a simple router that wraps httprouter.Router and allows for middleware chaining
func (*Router) DELETE ¶ added in v0.2.0
DELETE registers a handler for DELETE requests to the given pattern
func (*Router) HEAD ¶ added in v0.2.0
HEAD registers a handler for HEAD requests to the given pattern
func (*Router) OPTIONS ¶ added in v0.2.0
OPTIONS registers a handler for OPTIONS requests to the given pattern
func (*Router) PATCH ¶ added in v0.2.0
PATCH registers a handler for PATCH requests to the given pattern
func (*Router) POST ¶ added in v0.2.0
POST registers a handler for POST requests to the given pattern
func (*Router) ServeHTTP ¶ added in v0.2.0
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements the http.Handler interface for the Router type
type Settings ¶ added in v0.2.0
type Settings struct {
// RequestDisallowUnknownFields will disallow unknown fields in the request body,
// resulting in a 400 Bad Request response if a field is present that cannot be
// mapped to the model struct.
RequestDisallowUnknownFields bool
// RequestIdHeader will determine if the request ID should be read from the
// request header. If not set, the request ID will be generated.
RequestIdAcceptHeader bool
// LogRequestBody will determine if the request body will be logged
LogRequestBody bool
// LogLevel is the log level for the logger that will be used
LogLevel zerolog.Level
// LogFormat is the log format for the logger that will be used
LogFormat logging.LogFormat
// LogOutput is the output for the logger that will be used
// If not set, the output will be [os.Stdout]
LogOutput io.Writer
}
Settings is a struct that holds the application settings
type ValidationError ¶
type ValidationError struct {
// Parameter that failed validation
Parameter string `json:"parameter"`
// Type indicates where the parameter was located (header, path, query, body)
Type ParameterType `json:"type"`
// Error message describing the validation error
Message string `json:"message"`
} // @Name ValidationError
ValidationError defines the interface for a validation error @Description Detailed information about a validation error
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors represents multiple validation errors
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
Error implements the error interface