Documentation
¶
Index ¶
- Constants
- Variables
- func AddNewMapMethod(key string, methods []string)
- func AddSkipPath(path SkipPath, skip bool)
- func BasicToken(next http.HandlerFunc) http.HandlerFunc
- func CustomToken(next http.HandlerFunc) http.HandlerFunc
- func Delete(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
- func DeleteSkipPath(path SkipPath)
- func Get(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
- func GetContextValue(key interface{}, r *http.Request) interface{}
- func LogRequest(method, uri, eventID, form string, headers http.Header, rawBody []byte)
- func LogResponse(eventID string, res *httptest.ResponseRecorder)
- func NewRequestBodyMiddleware(keyListMethods string) core.Middleware
- func OpenAPIHandler(registry *Registry) http.HandlerFunc
- func ParamValidatorV0(v any) (string, error)
- func Patch(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
- func Post(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
- func ProcessRequest(next http.HandlerFunc) http.HandlerFunc
- func Put(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
- func RegisterNewAPIRequestReceiver(receiver core.APIRequestReceiver)
- func RegisterNewAPIResponseFormatter(formatter core.APIResponseFormatter)
- func RegisterNewAPIResponseWriter(writer core.APIResponseWriter)
- func RegisterNewAPISecurityGuarantor(guarantor core.APISecurityGuarantor)
- func RegisterParamValidator(paramValidator func(any) (errMsg string, err error))
- func RegisterTraceIDProvider(provider TraceIDProvider)
- func RequestHeaderJSON(next http.HandlerFunc) http.HandlerFunc
- func RequestHeaderSession(next http.HandlerFunc) http.HandlerFunc
- func SetContextValue(key, value interface{}, r *http.Request) *http.Request
- func SetRouteVars(vars map[string]string, r *http.Request) *http.Request
- func SwaggerUIHandler(openAPIURL string) http.HandlerFunc
- func UpdateRequestContext(requestData *RequestContext, r *http.Request) *http.Request
- func ValidateBasicToken(token string) (client, secret string, valid bool)
- func ValidateCustomToken(token string) (json.RawMessage, bool)
- func ValidateMethods(keyMapMethod, method string) bool
- func Write(data core.ResponseData, w http.ResponseWriter)
- type Components
- type DataType
- type EncryptedRequest
- type Error
- type ErrorResponse
- type Info
- type Informative
- type JSONEncryptedBody
- type JSONRequest
- type JSONRequestInfo
- type JSONResponse
- type JSONResponseInfo
- type MediaType
- type OpenAPI
- type OpenAPIParameter
- type Operation
- type Parameter
- type Registry
- func (registry *Registry) AddSecurityScheme(name string, scheme SecurityScheme)
- func (registry *Registry) Info() Info
- func (registry *Registry) Register(method string, path string, opts ...RouteOption) Route
- func (registry *Registry) Routes() []Route
- func (registry *Registry) SecuritySchemes() map[string]SecurityScheme
- type RequestBasic
- func (request *RequestBasic) GetEventID() Response
- func (request *RequestBasic) GetRequestBasicInfo() Response
- func (request *RequestBasic) GetRequestFullInfo() Response
- func (request *RequestBasic) GetSecurityToken() Response
- func (request *RequestBasic) GetUserID() Response
- func (request *RequestBasic) UnmarshalBody() Response
- type RequestBodyObject
- type RequestContext
- type RequestContextKey
- type RequestReceiver
- type RequestReceiverV2
- type Response
- func GetHeaderValueBool(key string, r *http.Request) (bool, Response)
- func GetHeaderValueFloat64(key string, r *http.Request) (float64, Response)
- func GetHeaderValueInt(key string, r *http.Request) (int, Response)
- func GetHeaderValueInt64(key string, r *http.Request) (int64, Response)
- func GetHeaderValueString(key string, r *http.Request) (string, Response)
- func GetQueryParamValueBool(queryParamName string, r *http.Request) (bool, Response)
- func GetQueryParamValueFloat64(queryParamName string, r *http.Request) (float64, Response)
- func GetQueryParamValueInt(queryParamName string, r *http.Request) (int, Response)
- func GetQueryParamValueInt64(queryParamName string, r *http.Request) (int64, Response)
- func GetQueryParamValueString(queryParamName string, r *http.Request) (string, Response)
- func GetRouteVarValueBool(urlVarName string, r *http.Request) (bool, Response)
- func GetRouteVarValueFloat64(urlVarName string, r *http.Request) (float64, Response)
- func GetRouteVarValueInt(urlVarName string, r *http.Request) (int, Response)
- func GetRouteVarValueInt64(urlVarName string, r *http.Request) (int64, Response)
- func GetRouteVarValueString(urlVarName string, r *http.Request) (string, Response)
- func UnmarshalBody(v interface{}, r *http.Request) Response
- type ResponseFormatter
- type ResponseObject
- type ResponseWriter
- type Route
- type RouteOption
- func Body(body interface{}) RouteOption
- func BodySchema(schema *Schema) RouteOption
- func Description(description string) RouteOption
- func Path(name string, typ DataType, required bool) RouteOption
- func Query(name string, typ DataType, required bool) RouteOption
- func Responds(status int, body interface{}) RouteOption
- func ResponseSchema(status int, description string, schema *Schema) RouteOption
- func ResponseStatus(status int, body interface{}) RouteOption
- func ResponseWithDescription(status int, description string, body interface{}) RouteOption
- func Security(name string) RouteOption
- func Status(status int, body interface{}) RouteOption
- func Summary(summary string) RouteOption
- func Tags(tags ...string) RouteOption
- type RouteResponse
- type Router
- type Schema
- type SecurityGuaranter
- type SecurityScheme
- type SkipPath
- type Success
- type TraceIDProvider
- type ValidateCredentials
- type Warning
Constants ¶
const MethodGetKey = "get"
MethodGetKey GET http method key ..
const MethodPatchKey = "patch"
MethodPatchKey PATCH http method key ..
const MethodPostKey = "post"
MethodPostKey POST http method key ..
const MethodPutKey = "put"
MethodPutKey PUT http method key ..
const PPMethodsKey = "pp"
PPMethodsKey POST and PUT http methods ..
const PPPGMethodsKey = "pppg"
PPPGMethodsKey POST, PUT, PATCH, and GET http methods ..
const PPPMethodsKey = "ppp"
PPPMethodsKey POST, PUT and PATCH http methods ..
const RequestDataContextContextKey = RequestContextKey("requestData")
RequestDataContextContextKey request data context key to finds request context
Variables ¶
var ( // DefaultInvalidAuthHeaderMsg default invalid authorization message. DefaultInvalidAuthHeaderMsg = "Invalid Authorization header!" DefaultBasicUnauthorizedMsg = "Invalid basic token" DefaultBearerUnauthorizedMsg = "Invalid bearer token" // CustomTokenPrefix custom token authorization method prefix. CustomTokenPrefix = "Bearer" DefaultCustomUnauthorizedMsg = fmt.Sprintf("Invalid %v token", CustomTokenPrefix) )
var ( // DefaultErrorTitle default error title. DefaultErrorTitle = "Error response!" // DefaultErrorMessage default error message. DefaultErrorMessage = "The service has not completed the operation!" // ErrorType error response type the value is "error". ErrorType core.ResponseType = "error" // InternalServerTitle internal server error title. InternalServerTitle = "Sorry!" // InternalServerMessage internal server error message. InternalServerMessage = "An error has occurred please try again later." UnauthorizedTitle = "Unauthorized!" UnauthorizedMessage = "User not authorized." )
var ( // DefaultInfoTitle default informative title. DefaultInfoTitle = "Information!" // DefaultInfoMessage default informative message. DefaultInfoMessage = "The request has been successful!" // InformativeType info response type the value is "info". InformativeType core.ResponseType = "info" // DefaultInfoCode default informative code. DefaultInfoCode = "0000" )
var ( // DefaultSuccessTitle default success title. DefaultSuccessTitle = "Successful!" // DefaultSuccessMessage default success message. DefaultSuccessMessage = "The request has been successful!" // SuccessType success response type the value is "success". SuccessType core.ResponseType = "success" // DefaultSuccessCode default success code. DefaultSuccessCode = "0000" )
var ( // DefaultWarningTitle default warning title. DefaultWarningTitle = "Alert!" // DefaultWarningMessage default warning message. DefaultWarningMessage = "The application has been successful but with potential problems!" // WarningType warning response type the value is "warning" WarningType core.ResponseType = "warning" // DefaultWarningCode default warning code. DefaultWarningCode = "0000" )
var ( // Username basic authentication // Default: admin // Change this, it's insecure. Username = "default" // Password basic authentication // Default: admin // Change this, it's insecure. Password = "default" )
var BlankSuccess = true
BlankSuccess contols if success include user feeback information
var CustomTokenValidatorFunc core.CustomTokenValidator
CustomTokenValidatorFunc define custom function to validate custom token.
var EventIDHeaderKey = "EventID"
EventIDHeaderKey event ID header key.
var Fatal func(...interface{}) = log.Fatal
Fatal wrapper function.
var GetRouteVar func(string, *http.Request) string = func(key string, r *http.Request) string {
return getRouteVarFromContext(key, r)
}
GetRouteVar returns the route variables for the current request, if any define it as: api.GetRouteVar = myCustomGetRouteVarFunc
var MiddlewaresChain = core.MiddlewaresChain
MiddlewaresChain provides syntactic sugar to create a new middleware which will be the result of chaining the ones received as parameters
var Print func(string, ...interface{}) = log.Printf
Print wrapper function.
var PrintError func(...interface{}) = log.Print
PrintError wrapper function.
var PrintFullEvent bool = false
PrintFullEvent set true value for allow print full event request
var RequestBody = NewRequestBodyMiddleware(PPPGMethodsKey)
RequestBody wrapper middleware
var ResponseCodes = struct { Success core.ResponseCode Informative core.ResponseCode Warning core.ResponseCode DefaultError core.ResponseCode InvalidJSON core.ResponseCode InvalidRequestURL core.ResponseCode ValidationError core.ResponseCode MissingVersionError core.ResponseCode Unauthorized core.ResponseCode ObjectNotFound core.ResponseCode RestrictResource core.ResponseCode InternalServerEerror core.ResponseCode ServiceUnavailable core.ResponseCode InvalidParams core.ResponseCode }{ Success: "0000", Informative: "0000", Warning: "0000", DefaultError: "E001", InvalidJSON: "E002", InvalidRequestURL: "E003", ValidationError: "E004", MissingVersionError: "E005", Unauthorized: "B001", RestrictResource: "B002", ObjectNotFound: "E006", InternalServerEerror: "E300", ServiceUnavailable: "E301", InvalidParams: "A101", }
ResponseCodes catalog
var SecurityTokenHeaderKey = "SecurityToken"
SecurityTokenHeaderKey session ID header key.
var SkipPaths map[SkipPath]bool
var TraceIDLength = 6
TraceIDLength specifies the number of characters to return from the beginning of the input trace ID.
var TraceVisibility = 1
TraceVisibility controls how trace information is included in the response message. - 1: Includes both event ID and response code. - 2: Includes only the Code. - 3: Includes only the event ID.
var UserIDHeaderKey = "UserID"
UserIDHeaderKey User ID header key.
Functions ¶
func AddNewMapMethod ¶
AddNewMapMethod add a new method in a map of methods.
func AddSkipPath ¶ added in v0.1.12
func BasicToken ¶
func BasicToken(next http.HandlerFunc) http.HandlerFunc
BasicToken validates basic authentication token middleware.
func CustomToken ¶
func CustomToken(next http.HandlerFunc) http.HandlerFunc
CustomToken middleware to validates custom token authorization method.
func Delete ¶ added in v0.1.13
func Delete(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
Delete registers a DELETE route in a router adapter.
func DeleteSkipPath ¶ added in v0.1.12
func DeleteSkipPath(path SkipPath)
func Get ¶ added in v0.1.13
func Get(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
Get registers a GET route in a router adapter.
func GetContextValue ¶ added in v0.1.1
GetContextValue gets requesst context value from context key.
func LogRequest ¶
LogRequest prints API request in log.
func LogResponse ¶
func LogResponse(eventID string, res *httptest.ResponseRecorder)
LogResponse prints API response in log.
func NewRequestBodyMiddleware ¶
func NewRequestBodyMiddleware(keyListMethods string) core.Middleware
NewRequestBodyMiddleware doc ...
func OpenAPIHandler ¶ added in v0.1.13
func OpenAPIHandler(registry *Registry) http.HandlerFunc
OpenAPIHandler returns a handler that serves the registry as OpenAPI JSON.
func ParamValidatorV0 ¶ added in v0.1.8
func Patch ¶ added in v0.1.13
func Patch(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
Patch registers a PATCH route in a router adapter.
func Post ¶ added in v0.1.13
func Post(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
Post registers a POST route in a router adapter.
func ProcessRequest ¶ added in v0.1.1
func ProcessRequest(next http.HandlerFunc) http.HandlerFunc
ProcessRequest process request information.
func Put ¶ added in v0.1.13
func Put(router Router, path string, handler http.HandlerFunc, opts ...RouteOption)
Put registers a PUT route in a router adapter.
func RegisterNewAPIRequestReceiver ¶ added in v0.1.1
func RegisterNewAPIRequestReceiver(receiver core.APIRequestReceiver)
RegisterNewAPIRequestReceiver inject a new implementation in the core.APIRequestReceiver interface.
func RegisterNewAPIResponseFormatter ¶
func RegisterNewAPIResponseFormatter(formatter core.APIResponseFormatter)
RegisterNewAPIResponseFormatter inject a new implementation in the APIResponseFormatter interface.
func RegisterNewAPIResponseWriter ¶
func RegisterNewAPIResponseWriter(writer core.APIResponseWriter)
RegisterNewAPIResponseWriter inject a new implementation in the core.APIResponseWriter interface.
func RegisterNewAPISecurityGuarantor ¶ added in v0.1.1
func RegisterNewAPISecurityGuarantor(guarantor core.APISecurityGuarantor)
RegisterNewAPISecurityGuarantor inject a new implementation in the core.APISecurityGuarantor interface
func RegisterParamValidator ¶ added in v0.1.8
RegisterParamValidator inject a new implementation in the Validator
func RegisterTraceIDProvider ¶ added in v0.1.14
func RegisterTraceIDProvider(provider TraceIDProvider)
RegisterTraceIDProvider configures the provider used to derive event IDs from context.
func RequestHeaderJSON ¶
func RequestHeaderJSON(next http.HandlerFunc) http.HandlerFunc
RequestHeaderJSON validate header Content-Type, is required and equal to application/json
func RequestHeaderSession ¶
func RequestHeaderSession(next http.HandlerFunc) http.HandlerFunc
RequestHeaderSession validates that session ID is valid.
func SetContextValue ¶ added in v0.1.1
SetContextValue sets requesst context value from context key.
func SetRouteVars ¶ added in v0.1.13
SetRouteVars stores route variables in the request context.
func SwaggerUIHandler ¶ added in v0.1.13
func SwaggerUIHandler(openAPIURL string) http.HandlerFunc
SwaggerUIHandler returns a handler that serves Swagger UI for an OpenAPI URL.
func UpdateRequestContext ¶ added in v0.1.1
func UpdateRequestContext(requestData *RequestContext, r *http.Request) *http.Request
UpdateRequestContext update request context.
func ValidateBasicToken ¶
ValidateBasicToken validate token with a basic auth token validation method.
func ValidateCustomToken ¶
func ValidateCustomToken(token string) (json.RawMessage, bool)
ValidateCustomToken validate token with a custom method.
func ValidateMethods ¶ added in v0.1.1
ValidateMethods validates if a method exist in a methods map.
func Write ¶ added in v0.1.1
func Write(data core.ResponseData, w http.ResponseWriter)
Write API response in JSON format in screen. You can to define response JSON format implemented the APIResponseFormatter interface.
Types ¶
type Components ¶ added in v0.1.13
type Components struct {
SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
}
Components contains reusable OpenAPI components.
type DataType ¶ added in v0.1.13
type DataType string
DataType describes primitive route parameter types.
type EncryptedRequest ¶ added in v0.1.1
type EncryptedRequest struct {
*core.RequestEncryptedData
}
EncryptedRequest documentation ...
func ProcessEncryptedBody ¶ added in v0.1.1
func ProcessEncryptedBody(r *http.Request) (*EncryptedRequest, error)
ProcessEncryptedBody API request. You can to define request url encoding format and how to validate it implemented the APIRequestReciver interface.
type Error ¶
type Error core.ResponseData
Error error response type the value is "error".
func Error401 ¶ added in v0.1.1
func Error401() Error
Error401 returns a new HTTP Unauthorized error cod. and unauthorized error defalut title and default message.
func Error403 ¶ added in v0.1.1
func Error403() Error
Error403 returns a new HTTP Forbiden error code and unauthorized error defalut title and default message.
func Error500 ¶ added in v0.1.1
Error500 returns a new HTTP Internal Server Error code. and internal server error default title and default mesage.
func Error500WithMsg ¶ added in v0.1.1
Error500WithMsg returns a new HTTP internal server error code with custom message.
func Error501 ¶ added in v0.1.1
Error501 returns a new HTTP Not Implement Error code. and internal server error default title and default mesage.
func ErrorWithMsg ¶ added in v0.1.1
ErrorWithMsg return a new HTTP Bad Request with custom message.
type ErrorResponse ¶ added in v0.1.13
type ErrorResponse struct {
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
ErrorResponse is a small reusable schema model for documented errors.
type Info ¶ added in v0.1.13
type Info struct {
Title string `json:"title"`
Version string `json:"version"`
Description string `json:"description,omitempty"`
}
Info contains the public API metadata rendered into OpenAPI.
type Informative ¶
type Informative core.ResponseData
Informative info response type the value is "info".
func (Informative) Write ¶
func (info Informative) Write(w http.ResponseWriter, r *http.Request)
Write informative message in screen.
type JSONEncryptedBody ¶ added in v0.1.1
JSONEncryptedBody struct used to parse the encrypted request and response body.
type JSONRequest ¶
type JSONRequest struct {
Header JSONRequestInfo `json:"header,omitempty"`
Content json.RawMessage `json:"content,omitempty"`
}
JSONRequest struct used to parse the request content section.
type JSONRequestInfo ¶ added in v0.1.1
type JSONRequestInfo struct {
UUID string `json:"uuid,omitempty"`
DeviceType string `json:"device_type,omitempty"`
DeviceBrand string `json:"device_brand,omitempty"`
DeviceModel string `json:"device_model,omitempty"`
OS string `json:"os,omitempty"`
OSVersion string `json:"os_version,omitempty"`
Lang string `json:"lang,omitempty"`
Timezone string `json:"timezone,omitempty"`
AppVersion string `json:"app_version,omitempty"`
AppBuildVersion string `json:"app_build_version,omitempty"`
AppName string `json:"app_name,omitempty"`
SecurityToken string `json:"token,omitempty"`
DeviceId string `json:"device_id,omitempty"`
DeviceSerial string `json:"device_serial,omitempty"`
Latitude string `json:"lat,omitempty"`
Longitude string `json:"lon,omitempty"`
}
JSONRequestInfo request info section fields for encrypted requests.
type JSONResponse ¶
type JSONResponse struct {
Header JSONResponseInfo `json:"header,omitempty"`
Content interface{} `json:"content,omitempty"`
}
JSONResponse response body structure contains the info section, with the response type and the messages for users and the content section, with the required data for the request
type JSONResponseInfo ¶
type JSONResponseInfo struct {
Type core.ResponseType `json:"type"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
Token string `json:"token,omitempty"`
Action string `json:"action,omitempty"`
EventID string `json:"event_id,omitempty"`
Info map[string]string `json:"info,omitempty"`
}
JSONResponseInfo response body info section
type MediaType ¶ added in v0.1.13
type MediaType struct {
Schema *Schema `json:"schema,omitempty"`
}
MediaType is an OpenAPI media type object.
type OpenAPI ¶ added in v0.1.13
type OpenAPI struct {
OpenAPI string `json:"openapi"`
Info Info `json:"info"`
Paths map[string]map[string]Operation `json:"paths"`
Components *Components `json:"components,omitempty"`
}
OpenAPI is the generated OpenAPI 3 document.
func GenerateOpenAPI ¶ added in v0.1.13
GenerateOpenAPI renders an OpenAPI 3.0 document from a registry.
type OpenAPIParameter ¶ added in v0.1.13
type OpenAPIParameter struct {
Name string `json:"name"`
In string `json:"in"`
Required bool `json:"required,omitempty"`
Description string `json:"description,omitempty"`
Schema *Schema `json:"schema,omitempty"`
}
OpenAPIParameter is an OpenAPI parameter object.
type Operation ¶ added in v0.1.13
type Operation struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
Parameters []OpenAPIParameter `json:"parameters,omitempty"`
RequestBody *RequestBodyObject `json:"requestBody,omitempty"`
Responses map[string]ResponseObject `json:"responses"`
Security []map[string][]string `json:"security,omitempty"`
}
Operation is an OpenAPI operation object.
type Parameter ¶ added in v0.1.13
type Parameter struct {
Name string
In string
Type DataType
Required bool
Description string
Schema *Schema
}
Parameter describes a query, path, header, or cookie parameter.
type Registry ¶ added in v0.1.13
type Registry struct {
// contains filtered or unexported fields
}
Registry stores route metadata for OpenAPI generation.
func NewRegistry ¶ added in v0.1.13
NewRegistry creates a metadata registry.
func (*Registry) AddSecurityScheme ¶ added in v0.1.13
func (registry *Registry) AddSecurityScheme(name string, scheme SecurityScheme)
AddSecurityScheme registers a reusable OpenAPI security scheme.
func (*Registry) Register ¶ added in v0.1.13
func (registry *Registry) Register(method string, path string, opts ...RouteOption) Route
Register stores a route and applies its declarative options.
func (*Registry) SecuritySchemes ¶ added in v0.1.13
func (registry *Registry) SecuritySchemes() map[string]SecurityScheme
SecuritySchemes returns a snapshot of configured security schemes.
type RequestBasic ¶
type RequestBasic struct {
JSONStruct interface{}
SessionID string
UserID string
EventID string
HTTPReq *http.Request
}
RequestBasic doc ...
func (*RequestBasic) GetEventID ¶ added in v0.1.1
func (request *RequestBasic) GetEventID() Response
GetEventID gets event ID by header key layout.
func (*RequestBasic) GetRequestBasicInfo ¶
func (request *RequestBasic) GetRequestBasicInfo() Response
GetRequestBasicInfo gets session ID, user ID and event ID.
func (*RequestBasic) GetRequestFullInfo ¶
func (request *RequestBasic) GetRequestFullInfo() Response
GetRequestFullInfo gets session ID, userID, event ID and unmarshal request body.
func (*RequestBasic) GetSecurityToken ¶ added in v0.1.1
func (request *RequestBasic) GetSecurityToken() Response
GetSecurityToken gets security token from user by header key layout.
func (*RequestBasic) GetUserID ¶
func (request *RequestBasic) GetUserID() Response
GetUserID gets id user ID by header key layout.
func (*RequestBasic) UnmarshalBody ¶
func (request *RequestBasic) UnmarshalBody() Response
UnmarshalBody parses request body to a struct.
type RequestBodyObject ¶ added in v0.1.13
type RequestBodyObject struct {
Required bool `json:"required,omitempty"`
Content map[string]MediaType `json:"content"`
}
RequestBodyObject is an OpenAPI requestBody object.
type RequestContext ¶ added in v0.1.10
type RequestContext struct {
*core.RequestDataContext
}
Request contains all information to process the API request. Wrapper of core.RequestDataContext
func Context ¶ added in v0.1.10
func Context(ctx context.Context) *RequestContext
func GetRequestContext ¶ added in v0.1.1
func GetRequestContext(r *http.Request) (*RequestContext, error)
GetRequestContext gets request data from http request context. This useful when you set Request type of core.RequestDataContext in http request context in a middleware implementation. Returns a core.RequestDataContext struct from api.RequestDataContextContextKey key.
func ProcessBody ¶ added in v0.1.1
func ProcessBody(r *http.Request) (*RequestContext, error)
ProcessBody API request. You can to define request JSON format and how to validate it implemented the APIRequestReciver interface.
func RContext ¶ added in v0.1.10
func RContext(ctx context.Context) (*RequestContext, error)
RContext gets request data from http request context. This useful when you set Request type of core.RequestDataContext in http request context in a middleware implementation. Returns a core.RequestDataContext struct from api.RequestDataContextContextKey key.
type RequestReceiver ¶ added in v0.1.1
type RequestReceiver struct{}
RequestReceiver implementation of core.APIRequestReceiver interface
func (RequestReceiver) GetRouteVar ¶ added in v0.1.1
func (receiver RequestReceiver) GetRouteVar(key string, r *http.Request) string
GetRouteVar returns the route variables for the current request, if any
func (RequestReceiver) ProcessBody ¶ added in v0.1.1
func (receiver RequestReceiver) ProcessBody(r *http.Request) (*core.RequestDataContext, error)
ProcessBody process API request body information.
func (RequestReceiver) ProcessEncryptedBody ¶ added in v0.1.1
func (receiver RequestReceiver) ProcessEncryptedBody(r *http.Request) (*core.RequestEncryptedData, error)
ProcessEncryptedBody process API request encription information.
type RequestReceiverV2 ¶ added in v0.1.1
type RequestReceiverV2 struct{}
RequestReceiverV2 implementation of core.APIRequestReceiver interface
func (RequestReceiverV2) GetRouteVar ¶ added in v0.1.1
func (receiver RequestReceiverV2) GetRouteVar(key string, r *http.Request) string
GetRouteVar returns the route variables for the current request, if any
func (RequestReceiverV2) ProcessBody ¶ added in v0.1.1
func (receiver RequestReceiverV2) ProcessBody(r *http.Request) (*core.RequestDataContext, error)
ProcessBody API request body information.
func (RequestReceiverV2) ProcessEncryptedBody ¶ added in v0.1.1
func (receiver RequestReceiverV2) ProcessEncryptedBody(r *http.Request) (*core.RequestEncryptedData, error)
ProcessEncryptedBody API request encription information.
type Response ¶
type Response interface {
Write(w http.ResponseWriter, r *http.Request)
}
Response wrapper to generate core responses.
func GetHeaderValueBool ¶
GetHeaderValueBool gets header values as bool.
func GetHeaderValueFloat64 ¶
GetHeaderValueFloat64 gets header value as float 64.
func GetHeaderValueInt ¶
GetHeaderValueInt gets header value as integer.
func GetHeaderValueInt64 ¶
GetHeaderValueInt64 gets header value as integer 64.
func GetHeaderValueString ¶
GetHeaderValueString gets header value as string.
func GetQueryParamValueBool ¶
GetQueryParamValueBool gets param value as bool.
func GetQueryParamValueFloat64 ¶
GetQueryParamValueFloat64 gets query param value as float 64.
func GetQueryParamValueInt ¶
GetQueryParamValueInt gets query param value as integer.
func GetQueryParamValueInt64 ¶
GetQueryParamValueInt64 gets query param value as integer 64.
func GetQueryParamValueString ¶
GetQueryParamValueString gets query param value as string.
func GetRouteVarValueBool ¶
GetRouteVarValueBool gets route variable value as bool.
func GetRouteVarValueFloat64 ¶
GetRouteVarValueFloat64 gets route variable value as float 64.
func GetRouteVarValueInt ¶
GetRouteVarValueInt gets route variable value as integer.
func GetRouteVarValueInt64 ¶
GetRouteVarValueInt64 gets route variable value as integer 64.
func GetRouteVarValueString ¶
GetRouteVarValueString gets route variable value as string.
func UnmarshalBody ¶
UnmarshalBody parses and validates request body to a struct
type ResponseFormatter ¶
type ResponseFormatter struct{}
ResponseFormatter implementation of core.APIResponseFormatter interface.
func (ResponseFormatter) Format ¶
func (formatter ResponseFormatter) Format(data core.ResponseData) *core.ResponseFormatted
Format the response body information.
type ResponseObject ¶ added in v0.1.13
type ResponseObject struct {
Description string `json:"description"`
Content map[string]MediaType `json:"content,omitempty"`
}
ResponseObject is an OpenAPI response object.
type ResponseWriter ¶
type ResponseWriter struct{}
ResponseWriter implementation of core.APIResponseWriter interface.
func (ResponseWriter) Write ¶
func (writer ResponseWriter) Write(response *core.ResponseFormatted, w http.ResponseWriter)
Write the API response in screen.
type Route ¶ added in v0.1.13
type Route struct {
Method string
Path string
Summary string
Description string
Tags []string
Body interface{}
BodySchema *Schema
Responses []RouteResponse
Parameters []Parameter
Security []string
}
Route describes a registered HTTP operation.
type RouteOption ¶ added in v0.1.13
type RouteOption func(*Route)
RouteOption mutates route metadata.
func Body ¶ added in v0.1.13
func Body(body interface{}) RouteOption
Body sets the request body model inferred with reflection.
func BodySchema ¶ added in v0.1.13
func BodySchema(schema *Schema) RouteOption
BodySchema sets a manual request body schema.
func Description ¶ added in v0.1.13
func Description(description string) RouteOption
Description sets the OpenAPI operation description.
func Path ¶ added in v0.1.13
func Path(name string, typ DataType, required bool) RouteOption
Path adds a path parameter.
func Query ¶ added in v0.1.13
func Query(name string, typ DataType, required bool) RouteOption
Query adds a query parameter.
func Responds ¶ added in v0.1.13
func Responds(status int, body interface{}) RouteOption
Responds is a readable alias for ResponseStatus.
func ResponseSchema ¶ added in v0.1.13
func ResponseSchema(status int, description string, schema *Schema) RouteOption
ResponseSchema adds a response with a manual schema.
func ResponseStatus ¶ added in v0.1.13
func ResponseStatus(status int, body interface{}) RouteOption
ResponseStatus adds a response model for a status code.
The shorter name Response is already an exported interface in this package, so this option keeps backward compatibility with the existing API.
func ResponseWithDescription ¶ added in v0.1.13
func ResponseWithDescription(status int, description string, body interface{}) RouteOption
ResponseWithDescription adds a response model and description.
func Security ¶
func Security(name string) RouteOption
Security adds a named security requirement to the operation.
func Status ¶ added in v0.1.13
func Status(status int, body interface{}) RouteOption
Status is a short alias for ResponseStatus.
func Summary ¶ added in v0.1.13
func Summary(summary string) RouteOption
Summary sets the OpenAPI operation summary.
func Tags ¶ added in v0.1.13
func Tags(tags ...string) RouteOption
Tags sets the OpenAPI operation tags.
type RouteResponse ¶ added in v0.1.13
RouteResponse describes an HTTP response for an operation.
type Router ¶ added in v0.1.13
type Router interface {
Handle(method string, path string, handler http.HandlerFunc, opts ...RouteOption)
}
Router is the minimal contract implemented by router adapters.
func NewMetadataRouter ¶ added in v0.1.13
NewMetadataRouter creates a router useful for tests and documentation-only registration.
type Schema ¶ added in v0.1.13
type Schema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
AdditionalProperties *Schema `json:"additionalProperties,omitempty"`
Required []string `json:"required,omitempty"`
Description string `json:"description,omitempty"`
Enum []interface{} `json:"enum,omitempty"`
Nullable bool `json:"nullable,omitempty"`
Ref string `json:"$ref,omitempty"`
Example interface{} `json:"example,omitempty"`
}
Schema is a small OpenAPI schema object.
func SchemaFromType ¶ added in v0.1.13
func SchemaFromType(value interface{}) *Schema
SchemaFromType infers an OpenAPI schema from a Go value or reflect.Type.
type SecurityGuaranter ¶ added in v0.1.1
type SecurityGuaranter struct{}
SecurityGuaranter implementation of core.APISecurityGuaranter interface.
func (*SecurityGuaranter) ValidateBasicToken ¶ added in v0.1.1
func (guaranter *SecurityGuaranter) ValidateBasicToken(token string) (client, secret string, valid bool)
ValidateBasicToken validate token with a basic auth token validation method.
func (*SecurityGuaranter) ValidateCustomToken ¶ added in v0.1.1
func (guaranter *SecurityGuaranter) ValidateCustomToken(token string, validator core.CustomTokenValidator) (json.RawMessage, bool)
ValidateCustomToken validate token with a custom method.
type SecurityScheme ¶ added in v0.1.13
type SecurityScheme struct {
Type string `json:"type"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
}
SecurityScheme is an OpenAPI security scheme object.
func APIKeySecurity ¶ added in v0.1.13
func APIKeySecurity(name string, in string) SecurityScheme
APIKeySecurity returns an API key security scheme.
func BasicSecurity ¶ added in v0.1.13
func BasicSecurity() SecurityScheme
BasicSecurity returns an HTTP basic security scheme.
func BearerSecurity ¶ added in v0.1.13
func BearerSecurity(format string) SecurityScheme
BearerSecurity returns an HTTP bearer security scheme.
type Success ¶
type Success core.ResponseData
Success success response type the value is "success".
func Success200 ¶ added in v0.1.1
func Success200() Success
Success200 returns a HTTP success response with status code 200.
func Success201 ¶ added in v0.1.1
func Success201() Success
Success201 returns a HTTP Created success response with status code 200.
func SuccessWithContent ¶ added in v0.1.1
func SuccessWithContent(content interface{}) Success
SuccessWithContent returns a HTTP OK response with conttent response.
func SuccessWithMsg ¶ added in v0.1.1
SuccessWithMsg returns a HTTP OK response with a custom message.
type TraceIDProvider ¶ added in v0.1.14
TraceIDProvider retrieves a trace ID from a context.
type ValidateCredentials ¶
ValidateCredentials func type.
var ValidateBasicAuthCredentialsFunc ValidateCredentials = validateCredentials
ValidateBasicAuthCredentialsFunc define custom function for validate basic authentication credential.
Source Files
¶
- api.go
- basic_request.go
- catalogs.go
- functions.go
- handlers.go
- middlewares.go
- openapi.go
- registry.go
- request_data.go
- request_structures.go
- request_validator.go
- request_validator_v2.go
- response.go
- response_error.go
- response_formatter.go
- response_informative.go
- response_structures.go
- response_success.go
- response_warning.go
- router.go
- schema.go
- security.go
- trace.go