webapi

package module
v0.0.0-...-fb1cdef Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2023 License: MIT Imports: 12 Imported by: 0

README

WebApi

GitHub Workflow Status (with event) Go Report Card GitHub gso.mod Go version GoDoc reference example Visitors GitHub

A web framework that prioritizes developer usability.

Description

This framework forces developer to write more structured, human-centric code.

Installation
go get github.com/KlyuchnikovV/webapi
Example of usage

The idea of this framework is to create services, each of which works with one model.

type RequestAPI struct{}

func (api *RequestAPI) Prefix() string {
    return "request"
}

Each service must implement 2 methods: Prefix and Routers:

  • Prefix gives route prefix and serves as name of your service;
  • Routers defines handlers, their paths and their mandatory parameters;

The handler described as a relative path to the handler wrapped in a request method (POST, GET ...) with additional middleware functions, including those for requesting mandatory parameters:

func (api *RequestAPI) Routers() map[string]webapi.RouterFunc {
    return map[string]webapi.RouterFunc{
        "get": webapi.GET(
            api.GetByID,
            parameter.Integer("id", placing.InQuery,
                options.Description("ID of the request."),
                validate.AND(validate.Greater(1), validate.Less(10)),
            ),
        ),
    }
}

Further, when requesting, all the necessary parameters will be checked for the presence and type (if the required parameter is missing, BadRequest error will be returned) and then will be available for use in handlers through the context ctx.

Also, through the context ctx, you can form a result or an error using predefined functions for the most used answers:

func (api *RequestAPI) GetByID(ctx *webapi.Context) error {
    var id = ctx.Integer("id", placing.InQuery)

    // Do something with id
    if id == 5 {
        return ctx.BadRequest("id can't be '%d'", id)
    }

    return ctx.OK(
        fmt.Sprintf("got id: '%d'", id),
    )
}

As a result, to create an application, it remains to create server with webapi.New passing tcp address and global (for every handler) prefix, register service and start the api.

func main() {
    w := webapi.New(
        ":8080",
        webapi.WithPrefix("api"),
        // Define all responses as JSON object
        webapi.ResponseAsJSON(
            // Define all responses use Result field to wrap response and
            //    Error field to wrap errors
            new(response.AsObject),
        ),
    )

    if err := w.RegisterServices(
        new(services.RequestAPI),
    ); err != nil {
        log.Fatal(err)
    }

    if err := w.Start(); err != nil {
        log.Fatal(err)
    }
}

Workable example of this api you can found here

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsIsResponse

func AsIsResponse(engine *Engine)

AsIsResponse - tells server to response objects without wrapping.

Types

type CORSOption

type CORSOption func(*cors)

func AllowedHeaders

func AllowedHeaders(headers ...string) CORSOption

func AllowedMethods

func AllowedMethods(methods ...string) CORSOption

func AllowedOrigins

func AllowedOrigins(origins ...string) CORSOption

type Context

type Context interface {

	// Headers - returns request headers.
	Headers() map[string][]string
	// All - returns all parsed parameters.
	All() map[placing.Placing]map[string]string
	// GetParameter - returns parameter value from defined place.
	GetParameter(string, placing.Placing) string
	// GetRequest - return http.Request object associated with request.
	GetRequest() *http.Request
	// Body - returns request body.
	// Body must be requested by 'api.Body(pointer)' or 'api.CustomBody(unmarshaler, pointer)'.
	Body() interface{}
	// Bool - returns boolean parameter.
	// Mandatory parameter should be requested by 'api.Bool'.
	// Otherwise, parameter will be obtained by key and its value will be checked for truth.
	Bool(string, placing.Placing) bool
	// Integer - returns integer parameter.
	// Mandatory parameter should be requested by 'api.Integer'.
	// Otherwise, parameter will be obtained by key and its value will be converted. to int64.
	Integer(string, placing.Placing) int64
	// Float - returns floating point number parameter.
	// Mandatory parameter should be requested by 'api.Float'.
	// Otherwise, parameter will be obtained by key and its value will be converted to float64.
	Float(string, placing.Placing) float64
	// String - returns String parameter.
	// Mandatory parameter should be requested by 'api.String'.
	// Otherwise, parameter will be obtained by key.
	String(string, placing.Placing) string
	// Time - returns date-time parameter.
	// Mandatory parameter should be requested by 'api.Time'.
	// Otherwise, parameter will be obtained by key and its value will be converted to time using 'layout'.
	Time(key string, layout string, paramPlacing placing.Placing) time.Time

	// ResponseWriter - returns http.ResponseWriter associated with request.
	ResponseWriter() http.ResponseWriter
	// Object - responses with provided custom code and body.
	// Body will be marshaled using service-defined object and marshaler.
	Object(code int, payload interface{}) error
	// WithourContent - responses with provided custom code and no body.
	WithoutContent(code int) error
	// Error - responses custom error with provided code and formatted string message.
	Error(code int, format string, args ...interface{}) error
	// OK - writes payload into json's 'result' field with 200 http code.
	OK(payload interface{}) error
	// Created - responses with 201 http code and no content.
	Created() error
	// NoContent - responses with 204 http code and no content.
	NoContent() error
	// BadRequest - responses with 400 code and provided formatted string message.
	BadRequest(format string, args ...interface{}) error
	// Forbidden - responses with 403 error code and provided formatted string message.
	Forbidden(format string, args ...interface{}) error
	// NotFound - responses with 404 error code and provided formatted string message.
	NotFound(format string, args ...interface{}) error
	// MethodNotAllowed - responses with 405 error code and provided formatted string message.
	MethodNotAllowed(format string, args ...interface{}) error
	// InternalServerError - responses with 500 error code and provided formatted string message.
	InternalServerError(format string, args ...interface{}) error
}

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine - server provider.

func New

func New(address string, configs ...Option) *Engine

func (*Engine) RegisterServices

func (e *Engine) RegisterServices(services ...ServiceAPI) error

RegisterServices - registering service routes.

func (*Engine) Start

func (e *Engine) Start() error

Start listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

Start always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed.

type Middleware

type Middleware func(*Service)

func UseCORS

func UseCORS(opts ...CORSOption) Middleware

type MiddlewaresAPI

type MiddlewaresAPI interface {
	Middlewares() []Middleware
}

type Option

type Option func(*Engine)

func ResponseAsJSON

func ResponseAsJSON(object types.Responser) Option

ResponseAsJSON - tells server to serialize responses as JSON using object as wrapper.

func ResponseAsXML

func ResponseAsXML(object types.Responser) Option

ResponseAsXML - tells server to serialize responses as XML using object as wrapper.

func Use

func Use(f func(*http.Server)) Option

Use - sets custom configuration function for http.Server.

func WithLogger

func WithLogger(log logger.Logger) Option

WithLogger - sets custom logger.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix - sets api's prefix.

func WithResponse

func WithResponse(object types.Responser) Option

WithResponse - tells server to use object as wrapper for all responses.

func WithSendingErrors

func WithSendingErrors(capacity int) Option

WithSendingErrors - sets errors channel capacity.

type OriginValidator

type OriginValidator func(string) bool

OriginValidator takes an origin string and returns whether or not that origin is allowed.

type Route

type Route func(Context) error

type RouterByPath

type RouterByPath func(*Service, string)

func CONNECT

func CONNECT(route Route, middlewares ...request.HandlerParams) RouterByPath

CONNECT - implements CONNECT api method call.

func DELETE

func DELETE(route Route, middlewares ...request.HandlerParams) RouterByPath

DELETE - implements DELETE api method call.

func GET

func GET(route Route, middlewares ...request.HandlerParams) RouterByPath

GET - implements GET api method call.

func HEAD(route Route, middlewares ...request.HandlerParams) RouterByPath

HEAD - implements HEAD api method call.

func OPTIONS

func OPTIONS(route Route, middlewares ...request.HandlerParams) RouterByPath

OPTIONS - implements OPTIONS api method call.

func PATCH

func PATCH(route Route, middlewares ...request.HandlerParams) RouterByPath

PATCH - implements PATCH api method call.

func POST

func POST(route Route, middlewares ...request.HandlerParams) RouterByPath

POST - implements POST api method call.

func PUT

func PUT(route Route, middlewares ...request.HandlerParams) RouterByPath

PUT - implements PUT api method call.

func TRACE

func TRACE(route Route, middlewares ...request.HandlerParams) RouterByPath

TRACE - implements TRACE api method call.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service - provides basic service methods.

func NewService

func NewService(engine *Engine, api ServiceAPI, path string) *Service

func (*Service) ServeHTTP

func (api *Service) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Body after or concurrently with the completion of the ServeHTTP call.

type ServiceAPI

type ServiceAPI interface {
	// Prefix - prefix of all paths for this service.
	Prefix() string

	// Routers returns the handlers and their relative paths (relative to the service) for registration.
	Routers() map[string]RouterByPath
}

Jump to

Keyboard shortcuts

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