Categorygithub.com/jgolang/api
modulepackage
0.1.11
Repository: https://github.com/jgolang/api.git
Documentation: pkg.go.dev

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

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

# Packages

No description provided by the author

# Functions

AddNewMapMethod add a new method in a map of methods.
BasicToken validates basic authentication token middleware.
No description provided by the author
CustomToken middleware to validates custom token authorization method.
Error400 returns a new HTTP Bad Request error code.
Error401 returns a new HTTP Unauthorized error cod.
Error403 returns a new HTTP Forbiden error code and unauthorized error defalut title and default message.
Error500 returns a new HTTP Internal Server Error code.
Error500WithMsg returns a new HTTP internal server error code with custom message.
Error501 returns a new HTTP Not Implement Error code.
ErrorWithMsg return a new HTTP Bad Request with custom message.
GetContextValue gets requesst context value from context key.
GetHeaderValueBool gets header values as bool.
GetHeaderValueFloat64 gets header value as float 64.
GetHeaderValueInt gets header value as integer.
GetHeaderValueInt64 gets header value as integer 64.
GetHeaderValueString gets header value as string.
GetQueryParamValueBool gets param value as bool.
GetQueryParamValueFloat64 gets query param value as float 64.
GetQueryParamValueInt gets query param value as integer.
GetQueryParamValueInt64 gets query param value as integer 64.
GetQueryParamValueString gets query param value as string.
GetRequestContext gets request data from http request context.
GetRouteVarValueBool gets route variable value as bool.
GetRouteVarValueFloat64 gets route variable value as float 64.
GetRouteVarValueInt gets route variable value as integer.
GetRouteVarValueInt64 gets route variable value as integer 64.
GetRouteVarValueString gets route variable value as string.
LogRequest prints API request in log.
LogResponse prints API response in log.
NewRequestBodyMiddleware doc ...
No description provided by the author
ProcessBody API request.
ProcessEncryptedBody API request.
ProcessRequest process request information.
RContext gets request data from http request context.
RegisterNewAPIRequestReceiver inject a new implementation in the core.APIRequestReceiver interface.
RegisterNewAPIResponseFormatter inject a new implementation in the APIResponseFormatter interface.
RegisterNewAPIResponseWriter inject a new implementation in the core.APIResponseWriter interface.
RegisterNewAPISecurityGuarantor inject a new implementation in the core.APISecurityGuarantor interface.
RegisterParamValidator inject a new implementation in the Validator.
RequestHeaderJSON validate header Content-Type, is required and equal to application/json.
RequestHeaderSession validates that session ID is valid.
SetContextValue sets requesst context value from context key.
Success200 returns a HTTP success response with status code 200.
Success201 returns a HTTP Created success response with status code 200.
SuccessWithContent returns a HTTP OK response with conttent response.
SuccessWithMsg returns a HTTP OK response with a custom message.
UnmarshalBody parses and validates request body to a struct.
UpdateRequestContext update request context.
ValidateBasicToken validate token with a basic auth token validation method.
ValidateCustomToken validate token with a custom method.
ValidateMethods validates if a method exist in a methods map.
Write API response in JSON format in screen.

# Constants

MethodGetKey GET http method key ..
MethodPatchKey PATCH http method key ..
MethodPostKey POST http method key ..
MethodPutKey PUT http method key ..
PPMethodsKey POST and PUT http methods ..
PPPGMethodsKey POST, PUT, PATCH, and GET http methods ..
PPPMethodsKey POST, PUT and PATCH http methods ..
RequestDataContextContextKey request data context key to finds request context.

# Variables

BlankSuccess contols if success include user feeback information.
CustomTokenPrefix custom token authorization method prefix.
CustomTokenValidatorFunc define custom function to validate custom token.
DefaultBasicUnauthorizedMsg default basic authetication method unauthorized message.
DefaultBearerUnauthorizedMsg default bearer authentication method unauthorized message.
DefaultCustomUnauthorizedMsg default custom token authorization method unauthorized message.
DefaultErrorMessage default error message.
DefaultErrorTitle default error title.
DefaultInfoCode default informative code.
DefaultInfoMessage default informative message.
DefaultInfoTitle default informative title.
DefaultInvalidAuthHeaderMsg default invalid authorization message.
DefaultSuccessCode default success code.
DefaultSuccessMessage default success message.
DefaultSuccessTitle default success title.
DefaultWarningCode default warning code.
DefaultWarningMessage default warning message.
DefaultWarningTitle default warning title.
ErrorType error response type the value is "error".
EventIDHeaderKey event ID header key.
Fatal wrapper function.
GetRouteVar returns the route variables for the current request, if any define it as: api.GetRouteVar = myCustomGetRouteVarFunc.
InformativeType info response type the value is "info".
InternalServerMessage internal server error message.
InternalServerTitle internal server error title.
MiddlewaresChain provides syntactic sugar to create a new middleware which will be the result of chaining the ones received as parameters.
Password basic authentication Default: admin Change this, it's insecure.
Print wrapper function.
PrintError wrapper function.
PrintFullEvent set true value for allow print full event request.
RequestBody wrapper middleware.
ResponseCodes catalog.
SecurityTokenHeaderKey session ID header key.
SuccessType success response type the value is "success".
TraceIDLength specifies the number of characters to return from the beginning of the input trace ID.
TraceVisibility controls how trace information is included in the response message.
UnauthorizedMessage unauthorized error message.
UnauthorizedTitle unauthorized error title.
UserIDHeaderKey User ID header key.
Username basic authentication Default: admin Change this, it's insecure.
ValidateBasicAuthCredentialsFunc define custom function for validate basic authentication credential.
WarningType warning response type the value is "warning".

# Structs

EncryptedRequest documentation ...
JSONEncryptedBody struct used to parse the encrypted request and response body.
JSONRequest struct used to parse the request content section.
JSONRequestInfo request info section fields for encrypted requests.
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.
JSONResponseInfo response body info section.
RequestBasic doc ...
Request contains all information to process the API request.
RequestReceiver implementation of core.APIRequestReceiver interface.
RequestReceiverV2 implementation of core.APIRequestReceiver interface.
ResponseFormatter implementation of core.APIResponseFormatter interface.
ResponseWriter implementation of core.APIResponseWriter interface.
SecurityGuaranter implementation of core.APISecurityGuaranter interface.

# Interfaces

Response wrapper to generate core responses.

# Type aliases

Error error response type the value is "error".
Informative info response type the value is "info".
RequestContextKey type.
Success success response type the value is "success".
ValidateCredentials func type.
Warning warning response type the value is "warning".