api

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2023 License: MIT Imports: 13 Imported by: 2

README

api

API developer helpful library

Documentation

Index

Constants

View Source
const MethodGetKey = "get"

MethodGetKey GET http method key ..

View Source
const MethodPatchKey = "patch"

MethodPatchKey PATCH http method key ..

View Source
const MethodPostKey = "post"

MethodPostKey POST http method key ..

View Source
const MethodPutKey = "put"

MethodPutKey PUT http method key ..

View Source
const PPMethodsKey = "pp"

PPMethodsKey POST and PUT http methods ..

View Source
const PPPGMethodsKey = "pppg"

PPPGMethodsKey POST, PUT, PATCH, and GET http methods ..

View Source
const PPPMethodsKey = "ppp"

PPPMethodsKey POST, PUT and PATCH http methods ..

View Source
const RequestDataContextKey = RequestContextKey("requestData")

RequestDataContextKey request data context key to finds request context

Variables

View Source
var (
	// DefaultInvalidAuthHeaderMsg default invalid authorization message.
	DefaultInvalidAuthHeaderMsg = "Invalid Authorization header!"

	// DefaultBasicUnauthorizedMsg default basic authetication method unauthorized message.
	DefaultBasicUnauthorizedMsg = "Invalid basic token"

	// DefaultBearerUnauthorizedMsg default bearer authentication method unauthorized message.
	DefaultBearerUnauthorizedMsg = "Invalid bearer token"

	// CustomTokenPrefix custom token authorization method prefix.
	CustomTokenPrefix = "Bearer"

	// DefaultCustomUnauthorizedMsg default custom token authorization method unauthorized message.
	DefaultCustomUnauthorizedMsg = fmt.Sprintf("Invalid %v token", CustomTokenPrefix)
)
View Source
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 error title.
	UnauthorizedTitle = "Unauthorized!"

	// UnauthorizedMessage unauthorized error message.
	UnauthorizedMessage = "User not authorized."
)
View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
var CustomTokenValidatorFunc core.CustomTokenValidator

CustomTokenValidatorFunc define custom function to validate custom token.

View Source
var EventIDHeaderKey = "EventID"

EventIDHeaderKey event ID header key.

View Source
var Fatal func(...interface{}) = log.Fatal

Fatal wrapper function.

View Source
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

View Source
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

View Source
var Print func(string, ...interface{}) = log.Printf

Print wrapper function.

View Source
var PrintError func(...interface{}) = log.Print

PrintError wrapper function.

View Source
var PrintFullEvent bool = false

PrintFullEvent set true value for allow print full event request

RequestBody wrapper middleware

View Source
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

View Source
var SecurityTokenHeaderKey = "SecurityToken"

SecurityTokenHeaderKey session ID header key.

View Source
var UserIDHeaderKey = "UserID"

UserIDHeaderKey User ID header key.

Functions

func AddNewMapMethod

func AddNewMapMethod(key string, methods []string)

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

func GetContextValue(key interface{}, r *http.Request) interface{}

GetContextValue gets requesst context value from context key.

func LogRequest

func LogRequest(method, uri, eventID, form string, headers http.Header, rawBody []byte)

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

func SetContextValue(key, value interface{}, r *http.Request) *http.Request

SetContextValue sets requesst context value from context key.

func UpdateRequestContext added in v0.1.1

func UpdateRequestContext(requestData *Request, r *http.Request) *http.Request

UpdateRequestContext update request context.

func ValidateBasicToken

func ValidateBasicToken(token string) (client, secret string, valid bool)

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

func ValidateMethods(keyMapMethod, method string) bool

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

func Error500WithMsg(msg string) Error

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

func ErrorWithMsg(msg string) Error

ErrorWithMsg return a new HTTP Bad Request with custom message.

func (Error) Write

func (err Error) Write(w http.ResponseWriter, r *http.Request)

Write response error in screen.

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

type JSONEncryptedBody struct {
	Data       string `json:"data"`
	DeviceUUID string `json:"deviceUUID"`
}

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

func GetRequestContext(r *http.Request) (*Request, error)

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.

func ProcessBody added in v0.1.1

func ProcessBody(r *http.Request) (*Request, error)

ProcessBody API request. You can to define request JSON format and how to validate it implemented the APIRequestReciver interface.

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 RequestContextKey added in v0.1.1

type RequestContextKey string

RequestContextKey type

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

func GetHeaderValueBool(key string, r *http.Request) (bool, Response)

GetHeaderValueBool gets header values as bool.

func GetHeaderValueFloat64

func GetHeaderValueFloat64(key string, r *http.Request) (float64, Response)

GetHeaderValueFloat64 gets header value as float 64.

func GetHeaderValueInt

func GetHeaderValueInt(key string, r *http.Request) (int, Response)

GetHeaderValueInt gets header value as integer.

func GetHeaderValueInt64

func GetHeaderValueInt64(key string, r *http.Request) (int64, Response)

GetHeaderValueInt64 gets header value as integer 64.

func GetHeaderValueString

func GetHeaderValueString(key string, r *http.Request) (string, Response)

GetHeaderValueString gets header value as string.

func GetQueryParamValueBool

func GetQueryParamValueBool(queryParamName string, r *http.Request) (bool, Response)

GetQueryParamValueBool gets param value as bool.

func GetQueryParamValueFloat64

func GetQueryParamValueFloat64(queryParamName string, r *http.Request) (float64, Response)

GetQueryParamValueFloat64 gets query param value as float 64.

func GetQueryParamValueInt

func GetQueryParamValueInt(queryParamName string, r *http.Request) (int, Response)

GetQueryParamValueInt gets query param value as integer.

func GetQueryParamValueInt64

func GetQueryParamValueInt64(queryParamName string, r *http.Request) (int64, Response)

GetQueryParamValueInt64 gets query param value as integer 64.

func GetQueryParamValueString

func GetQueryParamValueString(queryParamName string, r *http.Request) (string, Response)

GetQueryParamValueString gets query param value as string.

func GetRouteVarValueBool

func GetRouteVarValueBool(urlVarName string, r *http.Request) (bool, Response)

GetRouteVarValueBool gets route variable value as bool.

func GetRouteVarValueFloat64

func GetRouteVarValueFloat64(urlVarName string, r *http.Request) (float64, Response)

GetRouteVarValueFloat64 gets route variable value as float 64.

func GetRouteVarValueInt

func GetRouteVarValueInt(urlVarName string, r *http.Request) (int, Response)

GetRouteVarValueInt gets route variable value as integer.

func GetRouteVarValueInt64

func GetRouteVarValueInt64(urlVarName string, r *http.Request) (int64, Response)

GetRouteVarValueInt64 gets route variable value as integer 64.

func GetRouteVarValueString

func GetRouteVarValueString(urlVarName string, r *http.Request) (string, Response)

GetRouteVarValueString gets route variable value as string.

func UnmarshalBody

func UnmarshalBody(v interface{}, r *http.Request) Response

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

func SuccessWithMsg(msg string) Success

SuccessWithMsg returns a HTTP OK response with a custom message.

func (Success) Write

func (success Success) Write(w http.ResponseWriter, r *http.Request)

Write success response in screen.

type ValidateCredentials

type ValidateCredentials func(string, string) bool

ValidateCredentials func type.

var ValidateBasicAuthCredentialsFunc ValidateCredentials = validateCredentials

ValidateBasicAuthCredentialsFunc define custom function for validate basic authentication credential.

type Warning

type Warning core.ResponseData

Warning warning response type the value is "warning".

func (Warning) Write

func (warning Warning) Write(w http.ResponseWriter, r *http.Request)

Write warning response in screen.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL