api

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 19 Imported by: 2

README

API Developer Helper Library

Overview

This library is designed to standardize communication for API requests and responses in a microframework. It provides a consistent structure for headers and content, ensuring uniformity across different endpoints. The library helps developers easily wrap their endpoint-specific logic within a predefined request and response format.

Request Structure

The request JSON object consists of two main parts: header and content.

Header

The header contains metadata about the request and the device making the request. This includes information like device type, brand, OS version, and security token.

{
    "header": {
        "uuid": "2e67ee64-fb5e-11ed-be56-0242ac120003",
        "device_type": "user",
        "device_brand": "postman",
        "device_serial": "postman_device_serial",
        "device_id": "postman_device_id",
        "device_model": "postman",
        "os": "postman",
        "os_version": "0.0.0",
        "lang": "es",
        "timezone": "-6",
        "app_version": "1.3.0",
        "app_build_version": "0.1.0",
        "device_id": "",
        "device_serial": "",
        "lat": "",
        "lon": "",
        "token": "" // security token
    },
    "content": {
        // specific endpoint request object
    }
}
Content

The content part contains the actual data for the specific endpoint request. This is where the endpoint-specific request object goes.

Response Structure

The response JSON object also consists of two main parts: header and content.

Header

The header includes metadata about the response, such as the response status, messages, and security token.

{
    "header": {
        "title": "",
        "message": "",
        "type": "success",
        "code": "000",
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjNjMWM3ODBlLWQxMDAtNGEwZS05MTc3LTc1ZGRmY2Q0ZWU4MSIsInR5cGUiOiJhcHAiLCJleHAiOjE3MDkzOTQ0MTV9.f9I97DpJA1D2ahxq9-edCNnVOZVoLYBoQwuvAJf6F_8",
        "event_id": "f3c50980e8c71811b25b2319f0daf5a0",
        "action": "",
        "event_id": ""
    },
    "content": {
        // Specific endpoint response
    }
}
Content

The content part contains the actual data for the specific endpoint response. This is where the endpoint-specific response object goes.

Usage

Implementing a Standard Request

To implement a standard request using this library, follow these steps:

  1. Create the Request Object:

    • Fill in the header with the required metadata.
    • Add the specific endpoint request object within the content.
  2. Send the Request:

    • Use the appropriate method (e.g., HTTP POST) to send the request to the endpoint.
Example Request
{
    "header": {
        "uuid": "2e67ee64-fb5e-11ed-be56-0242ac120003",
        "device_type": "user",
        "device_brand": "postman",
        "device_serial": "postman_device_serial",
        "device_id": "postman_device_id",
        "device_model": "postman",
        "os": "postman",
        "os_version": "0.0.0",
        "lang": "es",
        "timezone": "-6",
        "app_version": "1.3.0",
        "app_build_version": "0.1.0",
        "token": "your-security-token"
    },
    "content": {
        "example_key": "example_value"
    }
}
Implementing a Standard Response

To implement a standard response using this library, follow these steps:

  1. Create the Response Object:

    • Fill in the header with the response metadata.
    • Add the specific endpoint response object within the content.
  2. Return the Response:

    • Return the response object as a JSON response to the client.
Example Response
{
    "header": {
        "title": "Request Successful",
        "message": "The request was processed successfully.",
        "type": "success",
        "code": "000",
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjNjMWM3ODBlLWQxMDAtNGEwZS05MTc3LTc1ZGRmY2Q0ZWU4MSIsInR5cGUiOiJhcHAiLCJleHAiOjE3MDkzOTQ0MTV9.f9I97DpJA1D2ahxq9-edCNnVOZVoLYBoQwuvAJf6F_8",
        "event_id": "f3c50980e8c71811b25b2319f0daf5a0",
        "action": "example_action"
    },
    "content": {
        "example_response_key": "example_response_value"
    }
}

Golang Implementation Example

Below is an example of how to use this library in a Golang project to create a standard success response. To use this library, you need to use the middleware function api.ProcessRequest()

See other helpful midlewares in the file ./middleware.go

Example Usage in an API Handler
package main

import (
	"net/http"

	"github.com/jgolang/api"
)

func handler(w http.ResponseWriter, r *http.Request) {
	response := api.Success200()
	response.Content = map[string]interface{}{
		"key": "value",
	}
	response.Write(w, r)
}

func main() {
    middlewaresChain := MiddlewaresChain(middleware.ProcessRequest)
	http.HandleFunc("/api/example", middlewaresChain(handler))
	http.ListenAndServe(":8080", nil)
}

In this example, the handler function creates a standard success response with a status code of 200 and some content. It then writes this response to the HTTP response writer. This ensures that all responses follow the same structure and include the necessary metadata.

Router-agnostic OpenAPI documentation

The package includes a router-agnostic registration layer for OpenAPI 3 and Swagger UI. The native adapter uses only Go's standard net/http package, while adapters for Gin, Echo, chi, gorilla/mux, or other routers should live in the application that chooses those routers.

The philosophy is to keep github.com/jgolang/api small and predictable: prefer Go's standard library and github.com/jgolang/... dependencies, with any exception made explicitly.

package main

import (
	"net/http"

	"github.com/jgolang/api"
	"github.com/jgolang/api/doc"
	"github.com/jgolang/api/envelope"
	"github.com/jgolang/api/stdadapter"
)

type CreateTaskRequest struct {
	Title string `json:"title"`
}

type TaskResponse struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

func createTask(w http.ResponseWriter, r *http.Request) {
	api.Success201().Write(w, r)
}

func listTasks(w http.ResponseWriter, r *http.Request) {
	api.Success200().Write(w, r)
}

func main() {
	docs := doc.New(doc.API{
		Title:   "Tasks API",
		Version: "1.0.0",
	})
	docs.AddSecurityScheme("bearerAuth", doc.BearerSecurity("JWT"))

	router := stdadapter.New(http.NewServeMux(), docs)

	api.Post(router, "/tasks", createTask,
		doc.Summary("Create task"),
		doc.Tags("tasks"),
		doc.Body(envelope.Request[CreateTaskRequest]()),
		doc.Security("bearerAuth"),
		doc.Status(201, envelope.Success[TaskResponse]()),
	)

	api.Get(router, "/tasks", listTasks,
		doc.Summary("List tasks"),
		doc.Tags("tasks"),
		doc.Status(200, envelope.Success[[]TaskResponse]()),
	)

	router.Handle("GET", "/openapi.json", doc.OpenAPIHandler(docs))
	router.Handle("GET", "/docs", doc.SwaggerUIHandler("/openapi.json"))

	http.ListenAndServe(":8080", router)
}

See docs/openapi.md for security schemes, schema tags, response aliases, and external adapter examples.

Trace IDs

The package does not depend on a tracing vendor. Applications can provide trace IDs through api.RegisterTraceIDProvider(...); see docs/tracing.md.

Contributing

If you have suggestions for how We could be improved, or want to report a bug, open an issue! We'd love all and any contributions.

For more, check out the Contributing Guide.

License

This project is licensed under the MIT License.

Support

If you find this repository helpful and would like to support its development, consider making a donation. Your contributions will help ensure the continued improvement and maintenance of this repository.

Thank you for your support!

ko-fi

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 RequestDataContextContextKey = RequestContextKey("requestData")

RequestDataContextContextKey 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 = "0000"
)
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 = "0000"
)
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 = "0000"
)
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 BlankSuccess = true

BlankSuccess contols if success include user feeback information

View Source
var CurrentRequestMode = RequestModePlain

CurrentRequestMode defines the active request parsing mode.

View Source
var CurrentResponseMode = ResponseModeEnvelope

CurrentResponseMode defines the active response formatting mode.

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(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

View Source
var LogRequestBody bool = false

LogRequestBody enables request body logging.

View Source
var LogResponseBody bool = false

LogResponseBody enables response body logging.

View Source
var MaxLoggedBodyBytes int = 2000

MaxLoggedBodyBytes limits logged request and response bodies when PrintFullEvent is false.

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

View Source
var SecurityTokenHeaderKey = "SecurityToken"

SecurityTokenHeaderKey session ID header key.

View Source
var SensitiveLogKeys = []string{
	"authorization",
	"token",
	"password",
	"secret",
	"credential",
	"apikey",
	"api-key",
	"key",
}

SensitiveLogKeys defines fields and headers that must be redacted in logs.

View Source
var SkipPaths map[SkipPath]bool
View Source
var TraceIDLength = 6

TraceIDLength specifies the number of characters to return from the beginning of the input trace ID.

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

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 AddSkipPath added in v0.1.12

func AddSkipPath(path SkipPath, skip bool)

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 ...doc.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 ...doc.RouteOption)

Get registers a GET route in a router adapter.

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 LogResponseWithDuration added in v0.2.1

func LogResponseWithDuration(eventID string, res *httptest.ResponseRecorder, duration time.Duration)

LogResponseWithDuration prints API response in log including request duration.

func NewRequestBodyMiddleware

func NewRequestBodyMiddleware(keyListMethods string) core.Middleware

NewRequestBodyMiddleware doc ...

func ParamValidatorV0 added in v0.1.8

func ParamValidatorV0(v any) (string, error)

func Patch added in v0.1.13

func Patch(router Router, path string, handler http.HandlerFunc, opts ...doc.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 ...doc.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 ...doc.RouteOption)

Put registers a PUT route in a router adapter.

func RegisterAdapter added in v0.2.0

func RegisterAdapter(name string, factory AdapterFactory)

RegisterAdapter registers a router adapter factory.

func RegisterAuth added in v0.2.0

func RegisterAuth(name string, provider AuthProvider)

RegisterAuth registers an authentication provider.

func RegisterCodec added in v0.2.0

func RegisterCodec(name string, codec Codec)

RegisterCodec registers a response serialization codec.

func RegisterCrypto added in v0.2.0

func RegisterCrypto(name string, provider CryptoProvider)

RegisterCrypto registers an encryption/decryption provider.

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

func RegisterParamValidator(paramValidator func(any) (errMsg string, err error))

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 RegisterTraceProvider added in v0.2.0

func RegisterTraceProvider(name string, provider TraceIDProvider)

RegisterTraceProvider registers a named trace ID provider.

func RegisterValidator added in v0.2.0

func RegisterValidator(name string, validator Validator)

RegisterValidator registers a validation provider.

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 SetRequestMode added in v0.2.1

func SetRequestMode(mode RequestMode)

SetRequestMode updates the request parsing mode.

func SetResponseMode added in v0.2.1

func SetResponseMode(mode ResponseMode)

SetResponseMode updates the response formatting mode.

func SetRouteVars added in v0.1.13

func SetRouteVars(vars map[string]string, r *http.Request) *http.Request

SetRouteVars stores route variables in the request context.

func UpdateRequestContext added in v0.1.1

func UpdateRequestContext(requestData *RequestContext, 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 AdapterFactory added in v0.2.0

type AdapterFactory func(target any, docs *doc.Docs) (Router, error)

AdapterFactory creates a Router from an adapter-specific target.

type AuthProvider added in v0.2.0

type AuthProvider interface {
	Authenticate(r *http.Request) (*AuthResult, error)
}

AuthProvider authenticates an HTTP request.

func AuthByName added in v0.2.0

func AuthByName(name string) (AuthProvider, error)

AuthByName returns a registered authentication provider.

type AuthResult added in v0.2.0

type AuthResult struct {
	Subject string
	Token   string
	Claims  map[string]any
}

AuthResult contains normalized authentication data returned by an AuthProvider.

type Codec added in v0.2.0

type Codec interface {
	ContentType() string
	Encode(w io.Writer, value any) error
}

Codec serializes response bodies.

func CodecByName added in v0.2.0

func CodecByName(name string) (Codec, error)

CodecByName returns a registered response serialization codec.

type CryptoProvider added in v0.2.0

type CryptoProvider interface {
	Encrypt(ctx context.Context, plaintext []byte) ([]byte, error)
	Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)
}

CryptoProvider encrypts and decrypts payload bytes.

func CryptoByName added in v0.2.0

func CryptoByName(name string) (CryptoProvider, error)

CryptoByName returns a registered encryption/decryption provider.

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(errs ...error) 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(errs ...error) 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, errs ...error) Error

Error500WithMsg returns a new HTTP internal server error code with custom message.

func Error501 added in v0.1.1

func Error501(errs ...error) 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, errs ...error) 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 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 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 RequestContextKey added in v0.1.1

type RequestContextKey string

RequestContextKey type

type RequestMode added in v0.2.1

type RequestMode string

RequestMode controls how request payloads are parsed.

const (
	RequestModeNone     RequestMode = "none"
	RequestModePlain    RequestMode = "plain"
	RequestModeEnvelope RequestMode = "envelope"
	RequestModeAuto     RequestMode = "auto"
)

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

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 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 ResponseMode added in v0.2.1

type ResponseMode string

ResponseMode controls how response payloads are formatted.

const (
	ResponseModeNone     ResponseMode = "none"
	ResponseModePlain    ResponseMode = "plain"
	ResponseModeEnvelope ResponseMode = "envelope"
)

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 Router added in v0.1.13

type Router interface {
	Handle(method string, path string, handler http.HandlerFunc, opts ...doc.RouteOption)
}

Router is the minimal contract implemented by router adapters.

func NewRouter added in v0.2.0

func NewRouter(name string, target any, docs *doc.Docs) (Router, error)

NewRouter creates a Router from a registered adapter factory.

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 SkipPath added in v0.1.12

type SkipPath string

func GenSkipPath added in v0.1.12

func GenSkipPath(method string, path string) SkipPath

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 TraceIDProvider added in v0.1.14

type TraceIDProvider interface {
	TraceID(context.Context) string
}

TraceIDProvider retrieves a trace ID from a context.

func TraceProviderByName added in v0.2.0

func TraceProviderByName(name string) (TraceIDProvider, error)

TraceProviderByName returns a registered trace ID provider.

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 Validator added in v0.2.0

type Validator interface {
	Validate(value any) error
}

Validator validates a decoded value.

func ValidatorByName added in v0.2.0

func ValidatorByName(name string) (Validator, error)

ValidatorByName returns a registered validation provider.

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
Package doc contains OpenAPI documentation metadata, schema generation, and handlers.
Package doc contains OpenAPI documentation metadata, schema generation, and handlers.
Package envelope contains shared JSON request and response envelope contracts.
Package envelope contains shared JSON request and response envelope contracts.

Jump to

Keyboard shortcuts

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