Documentation ¶
Index ¶
- Constants
- Variables
- func AddNewMapMethod(key string, methods []string)
- func BasicToken(next http.HandlerFunc) http.HandlerFunc
- func CustomToken(next http.HandlerFunc) http.HandlerFunc
- 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 ProcessRequest(next http.HandlerFunc) http.HandlerFunc
- func RegisterNewAPIRequestReceiver(receiver core.APIRequestReceiver)
- func RegisterNewAPIResponseFormatter(formatter core.APIResponseFormatter)
- func RegisterNewAPIResponseWriter(writer core.APIResponseWriter)
- func RegisterNewAPISecurityGuarantor(guarantor core.APISecurityGuarantor)
- 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 UpdateRequestContext(requestData *Request, 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 EncryptedRequest
- type Error
- type Informative
- type JSONEncryptedBody
- type JSONRequest
- type JSONRequestInfo
- type JSONResponse
- type JSONResponseInfo
- type Request
- 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 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 ResponseWriter
- type SecurityGuaranter
- type Success
- 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 RequestDataContextKey = RequestContextKey("requestData")
RequestDataContextKey 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 = "000" )
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 = "000" )
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 = "000" )
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 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(string, *http.Request) string { PrintError("Define a GetRouteVar function in this package") return "" }
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 }{ Success: "000", Informative: "000", Warning: "000", DefaultError: "E001", InvalidJSON: "E002", InvalidRequestURL: "E003", ValidationError: "E004", MissingVersionError: "E005", Unauthorized: "S001", RestrictResource: "S002", ObjectNotFound: "E006", InternalServerEerror: "I300", ServiceUnavailable: "I301", }
ResponseCodes catalog
var SecurityTokenHeaderKey = "SecurityToken"
SecurityTokenHeaderKey session ID header key.
var UserIDHeaderKey = "UserID"
UserIDHeaderKey User ID header key.
Functions ¶
func AddNewMapMethod ¶
AddNewMapMethod add a new method in a map of methods.
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 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 ProcessRequest ¶ added in v0.1.1
func ProcessRequest(next http.HandlerFunc) http.HandlerFunc
ProcessRequest process request information.
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 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 UpdateRequestContext ¶ added in v0.1.1
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 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 Error400 ¶ added in v0.1.1
func Error400() Error
Error400 returns a new HTTP Bad Request error code.
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
func Error500() Error
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
func Error501() Error
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 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"` }
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 Request ¶ added in v0.1.1
type Request struct {
*core.RequestData
}
Request contains all information to process the API request. Wrapper of core.RequestData
func GetRequestContext ¶ added in v0.1.1
GetRequestContext gets request data from http request context. This useful when you set Request type of core.RequestData in http request context in a middleware implementation. Returns a core.RequestData struct from api.RequestDataContextKey key.
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 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.RequestData, 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.RequestData, 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 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 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 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 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 ValidateCredentials ¶
ValidateCredentials func type.
var ValidateBasicAuthCredentialsFunc ValidateCredentials = validateCredentials
ValidateBasicAuthCredentialsFunc define custom function for validate basic authentication credential.