engi

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

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

Go to latest
Published: Jan 31, 2024 License: MIT Imports: 16 Imported by: 0

README

Engi

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/engi
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() engi.Routes {
    return engi.Routes{
        "get": engi.GET(api.GetByID,
            parameter.Integer("id", placing.InQuery,
                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 context.Context,
    request engi.Request,
    response engi.Response,
) 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 engi.New passing tcp address and global (for every handler) prefix, register service and start the api.

func main() {
    w := engi.New(
        ":8080",
        engi.WithPrefix("api"),
        // Define all responses as JSON object
        engi.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

View Source
var (
	AllowedHeaders = cors.AllowedHeaders
	AllowedMethods = cors.AllowedMethods
	AllowedOrigins = cors.AllowedOrigins
)
View Source
var (
	NoAuth     = auth.NoAuth
	BasicAuth  = auth.Basic
	BearerAuth = auth.Bearer // TODO: remake it
	APIKeyAuth = func(key, value string, place AuthKeyPlacing) request.Middleware {
		return auth.APIKey(key, value, placing.Placing(place))
	}
)
View Source
var (
	ErrMethodNotAppliable = fmt.Errorf("method not appliable for path")
	ErrPathNotFound       = fmt.Errorf("path not found for method")
)

Functions

func AsIsResponse

func AsIsResponse(engine *Engine)

AsIsResponse - tells server to response objects without wrapping.

Types

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)

type Middlewares

type Middlewares []Middleware

type MiddlewaresAPI

type MiddlewaresAPI interface {
	Middlewares() []Register
}

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(handler slog.Handler) 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.

type Register

type Register middlewares.Register

func UseAuthorization

func UseAuthorization(option request.Middleware) Register

func UseCORS

func UseCORS(opts ...cors.CORSOption) Register

type Request

type Request request.Requester

type Response

type Response response.Responser

type Route

type Route func(ctx context.Context, request Request, response Response) error

type RouteByPath

type RouteByPath func(*Service, string) error

func CONNECT

func CONNECT(route Route, middlewares ...Register) RouteByPath

CONNECT - implements CONNECT api method call.

func DELETE

func DELETE(route Route, middlewares ...Register) RouteByPath

DELETE - implements DELETE api method call.

func GET

func GET(route Route, middlewares ...Register) RouteByPath

GET - implements GET api method call.

func HEAD(route Route, middlewares ...Register) RouteByPath

HEAD - implements HEAD api method call.

func OPTIONS

func OPTIONS(route Route, middlewares ...Register) RouteByPath

OPTIONS - implements OPTIONS api method call.

func PATCH

func PATCH(route Route, middlewares ...Register) RouteByPath

PATCH - implements PATCH api method call.

func POST

func POST(route Route, middlewares ...Register) RouteByPath

POST - implements POST api method call.

func PUT

func PUT(route Route, middlewares ...Register) RouteByPath

PUT - implements PUT api method call.

func TRACE

func TRACE(route Route, middlewares ...Register) RouteByPath

TRACE - implements TRACE api method call.

type Routes

type Routes map[string]RouteByPath

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

func (srv *Service) Middlewares() []Register

func (*Service) Serve

func (srv *Service) Serve(
	w http.ResponseWriter, r *http.Request, uri string,
) error

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() Routes
}

Jump to

Keyboard shortcuts

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