webfmwk

package module
v3.2.4 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2020 License: MIT Imports: 23 Imported by: 0

README

Build Status codecov GoDoc GolangCI Go Report Card CodeFactor DeepSource CII Best Practices License

What

webfmwk is a go web API framework. Proprietary of Frafos GmbH.

It was designed to be a minimalist go web framework supporting JSON API.

The purpose of the framework is to use as few external library than possible.

TODO: explain that perf is not the purpose. that's why panic are used - more user friendly.

dep

what for
gorilla/mux for a easy & robust routing logic
gorilla/hanlers for some useful already coded middlewares
gorilla/schema for some useful already coded middlewares
validator use by the custom implementation of the context
json-iterator use by the custom implementation of the context

Test

Simply run make

How to use it

Their are a few mains in the ./exmaple directory. The content of the mains or used later in the README.md.

Example

Hello world !

Reach the endpoint with curl -X GET 'http://localhost:4242/hello'.

hello world

package main

import (
    "net/http"

    w "github.com/burgesQ/webfmwk/v3"
)

func main() {
    // create server
    s := w.InitServer()

    s.GET("/hello", func(c w.IContext) {
        c.JSONBlob(http.StatusOK, []byte(`{ "message": "hello world" }`))
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

fetch query param

Reach the endpoint with curl -X GET 'http://localhost:4242/hello?&pjson&turlu=tutu'.

query param

package main

import (
    "net/http"

    w "github.com/burgesQ/webfmwk/v3"
    "github.com/burgesQ/webfmwk/v3/log"
)

func main() {
    // create server
    s := w.InitServer()

    s.GET("/hello", func(c w.IContext) {
        var (
            queries   = c.GetQueries()
            pjson, ok = c.GetQuery("pjson")
        )
        if ok {
            c.log.Errorf("%#v", pjson)
        }
        c.JSON(http.StatusOK, queries)
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

fetch url params

Reach the endpoint with curl -X GET 'http://localhost:4242/hello/you'.

url param

package main

import (
    "net/http"

    w "github.com/burgesQ/webfmwk/v3"
)

func main() {
    // create server
    s := w.InitServer()

    s.GET("/hello/{id}", func(c w.IContext) {
        c.JSONBlob(http.StatusOK, []byte(`{ "id": "`+c.GetVar("id")+`" }`))
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

deserialize body / query param / validate

Reach the endpoint with curl -X POST -d '{"name": "test", "age": 12}' -H "Content-Type: application/json" "http://localhost:4242/hello".

Note that the webfmwk only accept application/json content (for the moment ?).

Don't hesitate to play with the payload to inspect the behavior of the Validate method.

The struct annotation are done via the validator and schema keywords. Please refer to the validator documentation and the gorilla/schema one.

POST content

package main

import (
    "net/http"

    w "github.com/burgesQ/webfmwk/v3"
)

type (
    // Content hold the body of the request
    Content struct {
        Name string `schema:"name" json:"name" validate:"omitempty"`
        Age  int    `schema:"age" json:"age" validate:"gte=1"`
    }

    // QueryParam hold the query params
    QueryParam struct {
        PJSON bool `schema:"pjson" json:"pjson"`
        Val   int  `schema:"val" json:"val" validate:"gte=1"`
    }

    // Payload hold the output of the endpoint
    Payload struct {
        Content Content    `json:"content"`
        QP      QueryParam `json:"query_param"`
    }
)

func main() {
    // create server
    s := w.InitServer()

    s.POST("/hello", func(c w.IContext) {
        var out = Payload{}

        c.FetchContent(&out.content)
        c.Validate(out.content)
        c.DecodeQP(&out.qp)
        c.Validate(out.qp)

        c.JSON(http.StatusOK, out)
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4244")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Set a base url

Reach the endpoint with curl -X GET 'http://localhost:4242/api/v1/test and curl -X GET 'http://localhost:4242/api/v2/test.

base url

package main

import (
    "github.com/burgesQ/webfmwk/v3"
)

var (
    routes = webfmwk.RoutesPerPrefix{
        "/api/v1": {
            {
                Verbe: "GET",
                Path:  "/test",
                Name:  "test v1",
                Handler: func(c webfmwk.IContext) {
                    c.JSONOk("v1 ok")
                },
            },
        },
        "/api/v2": {
            {
                Verbe: "GET",
                Path:  "/test",
                Name:  "test v2",
                Handler: func(c webfmwk.IContext) {
                    c.JSONOk("v2 ok")
                },
            },
        },
    }
)

func main() {

    s := webfmwk.InitServer()

    s.RouteApplier(routes)

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internaly
    defer s.WaitAndStop()

}

Use tls

Use the method Server.StartTLS(addr, certPath, keyPath string).

use tls

package main

import (
    w "github.com/burgesQ/webfmwk/v3"
)

func main() {
    // init server w/ ctrl+c support
    s := w.InitServer(WithCtrlC())

    s.GET("/test", func(c w.IContext) error {
        return c.JSONOk("ok")
    })

    // start asynchronously on :4242
    go func() {
        s.StartTLS(":4242", TLSConfig{
            Cert:     "/path/to/cert",
            Key:      "/path/to/key",
            Insecure: true,
        })
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Register a custom logger

The logger must implement the webfmwk/log.ILog interface.

custom logger

package main

import (
    w "github.com/burgesQ/webfmwk/v3"
    "github.com/burgesQ/webfmwk/v3/log"
)

// GetLogger return a log.ILog interface
var logger = log.GetLogger()

func main() {
    s := w.InitServer(WithLogger(logger))

    s.GET("/test", func(c w.IContext) error {
        return c.JSONOk("ok")
    })

    // start asynchronously on :4242
    go func() {
        s.StartTLS(":4242", TLSConfig{
            Cert:     "/path/to/cert",
            Key:      "/path/to/key",
            Insecure: true,
        })
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Register a extended context

Create a struct that extend webfmwk.Context.

Then, add a middleware to extend the context using the Server.SetCustomContext(func(c *Context) IContext)

extend context

package main

import (
    w "github.com/burgesQ/webfmwk/v3"
)

type customContext struct {
    w.Context
    customVal string
}

func main() {
    // init server w/ ctrl+c support
    s := w.InitServer(WithCustomContext(func(c *w.Context) w.IContext {
        ctx := &customContext{*c, "42"}
        return ctx
    })

    s.GET("/test", func(c w.IContext) {
        ctx := c.(*customContext)
        c.JSONOk(ctx.customVal)
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4244")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Register middlewares

Import github.com/burgesQ/webfmwk/v3/middleware

extend middleware

package main

import (
    w "github.com/burgesQ/webfmwk/v3"
    m "github.com/burgesQ/webfmwk/v3/middleware"
)

func main() {

    // init server w/ ctrl+c support
    s := w.InitServer(WithMiddlewars(m.Logging, m.Security)

    s.GET("/test", func(c w.IContext) error {
        return c.JSONOk("ok")
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Swagger doc compatibility

Import github.com/swaggo/http-swagger.

Then, from a browser reach :4242/api/doc/index.html.

Or, run curl -X GET 'http://localhost:4242/api/doc/swagger.json'.

swagger doc

package main

import (
    w "github.com/burgesQ/webfmwk/v3"
    httpSwagger "github.com/swaggo/http-swagger"
)

type Answer struct {
    Message string `json:"message"`
}

// @Summary hello world
// @Description Return a simple greeting
// @Param pjson query bool false "return a pretty JSON"
// @Success 200 {object} db.Reply
// @Produce application/json
// @Router /hello [get]
func hello(c w.IContext) error {
    return c.JSONOk(Answer{"ok"})
}

// @title hello world API
// @version 1.0
// @description This is an simple API
// @termsOfService https://www.youtube.com/watch?v=DLzxrzFCyOs
// @contact.name Quentin Burgess
// @contact.url github.com/burgesQ
// @contact.email quentin@frafos.com
// @license.name GFO
// @host localhost:4242
func main() {
    // init server w/ ctrl+c support
    s := w.InitServer(WithDocHandler(httpSwagger.WrapHandler))

    s.SetPrefix("/api")

    s.GET("/test", func(c w.IContext) error {
        return c.JSONOk("ok")
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Add worker

Use the Server.GetWorkerLauncher() method.

Run the test main and wait 10 sec.

extra worker

package main

import (
    "time"

    w "github.com/burgesQ/webfmwk/v3"
    "github.com/burgesQ/webfmwk/v3/log"
)

func main() {
    log.SetLogLevel(log.LogDEBUG)
    var (
      s  = w.InitServer()
      wl = s.GetLauncher()
   )


    s.GET("/test", func(c w.IContext) {
        c.JSONOk("ok")
    })

    wl.Start("custom worker", func() error {
        time.Sleep(10 * time.Second)
        log.Debugf("done")
        return nil
    })

    // start asynchronously on :4242
    go func() {
        s.Start(":4242")
    }()

    // ctrl+c is handled internally
    defer s.WaitAndStop()
}

Documentation

Overview

Package webfmwk implements an minimalist Go web framework

Example:

  package main

  import (
    w "github.com/burgesQ/webfmwk/v3"
  )

  type Context struct {
    webfmwk.IContext
    content string
  }

  // Handler
  func hello(c w.IContext) error {
    return c.JSONOk("Hello, World!")
  }

  func main() {
    // Echo instance
    s := w.InitServer(
     webfmwk.EnableCheckIsUp()
		webfmwk.WithCORS(),
		webfmwk.WithLogger(log.GetLogger()),
		webfmwk.WithMiddlewars(
			middleware.Logging,
			middleware.Security),
		webfmwk.WithCustomContext(func(c *webfmwk.Context) webfmwk.IContext {
			return &Context{
				Context:  *c,
				content: "testing",
			}
		}))

    // Routes
    s.GET("/hello", hello)

    // start server on :4242
    go func() {
      s.Start(":4242")
    }()

    // ctrl+c is handled internaly
    defer s.WaitAndStop()
  }

Learn more at https://github.com/burgesQ/webfmwk

Index

Constants

View Source
const (
	GET    = "GET"
	POST   = "POST"
	PATCH  = "PATCH"
	PUT    = "PUT"
	DELETE = "DELETE"
)

Variables

Functions

func AssignRequestID added in v3.2.0

func AssignRequestID(ctx context.Context) context.Context

AssignRequestID will attach a brand new request ID to a http request

func GetLogger

func GetLogger() log.ILog

GetLogger return an instance of the ILog interface used

func GetRequestID added in v3.2.0

func GetRequestID(ctx context.Context) string

GetRequestID will get reqID from a http request and return it as a string

func Shutdown

func Shutdown(ctx context.Context)

Shutdown terminate all running servers. Call shutdown with a context.context on each http(s) server.

Types

type AnonymousError

type AnonymousError struct {
	Error string `json:"error"`
}

AnonymousError struct is used to answer error

type Context

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

Context implement the IContext interface It hold the data used by the request

func (*Context) CheckHeader

func (c *Context) CheckHeader()

CheckHeader implement IContext

func (*Context) DecodeQP

func (c *Context) DecodeQP(dest interface{})

DecodeQP implement IContext

func (*Context) FetchContent

func (c *Context) FetchContent(dest interface{})

FetchContent implement IContext It load payload in the dest interface{} using the system json library

func (*Context) GetContext

func (c *Context) GetContext() context.Context

GetContent implement IContext

func (*Context) GetQueries

func (c *Context) GetQueries() map[string][]string

GetQueries implement IContext

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery implement IContext

func (*Context) GetRequest added in v3.2.4

func (c *Context) GetRequest() *http.Request

GetRequest implement IContext

func (*Context) GetRequestID added in v3.2.0

func (c *Context) GetRequestID() string

SetRequest implement IContext

func (*Context) GetVar

func (c *Context) GetVar(key string) string

GetVar implement IContext

func (*Context) IsPretty

func (c *Context) IsPretty() bool

IsPretty implement IContext

func (*Context) JSON

func (c *Context) JSON(statusCode int, content interface{})

JSON create a JSON response based on the param content.

func (*Context) JSONAccepted

func (c *Context) JSONAccepted(content interface{})

JSONOk implement IContext

func (*Context) JSONBadRequest

func (c *Context) JSONBadRequest(content interface{})

JSONBadRequest implement IContext

func (*Context) JSONBlob

func (c *Context) JSONBlob(statusCode int, content []byte)

JSONBlob sent a JSON response already encoded

func (*Context) JSONConflict

func (c *Context) JSONConflict(content interface{})

JSONConflict implement IContext

func (*Context) JSONCreated

func (c *Context) JSONCreated(content interface{})

JSONCreated implement IContext

func (*Context) JSONInternalError

func (c *Context) JSONInternalError(content interface{})

JSONInternalError implement IContext

func (*Context) JSONNoContent

func (c *Context) JSONNoContent()

JSONNoContent implement IContext

func (*Context) JSONNotFound

func (c *Context) JSONNotFound(content interface{})

JSONNotFound implement IContext

func (*Context) JSONNotImplemented

func (c *Context) JSONNotImplemented(content interface{})

JSONNotImplemented implement IContext

func (*Context) JSONOk

func (c *Context) JSONOk(content interface{})

JSONOk implement IContext

func (*Context) JSONUnprocessable

func (c *Context) JSONUnprocessable(content interface{})

JSONUnprocessable implement IContext

func (*Context) OwnRecover

func (c *Context) OwnRecover()

OwnRecover implement IContext

func (*Context) SendResponse

func (c *Context) SendResponse(statusCode int, content []byte, headers ...[2]string)

Send Response implement IContext

func (*Context) SetContext

func (c *Context) SetContext(ctx context.Context) IContext

SetContext implement IContext

func (*Context) SetLogger

func (c *Context) SetLogger(logger log.ILog) IContext

SetLogger implement IContext

func (*Context) SetQuery

func (c *Context) SetQuery(q map[string][]string) IContext

SetQuery implement IContext

func (*Context) SetRequest

func (c *Context) SetRequest(r *http.Request) IContext

SetRequest implement IContext

func (*Context) SetRequestID added in v3.2.0

func (c *Context) SetRequestID(id string) IContext

SetRequest implement IContext

func (*Context) SetVars

func (c *Context) SetVars(v map[string]string) IContext

SetVars implement IContext

func (*Context) SetWriter

func (c *Context) SetWriter(w http.ResponseWriter) IContext

SetWriter implement IContext

func (*Context) Validate

func (c *Context) Validate(dest interface{})

Validate implement IContext this implemt use validator to anotate & check struct

type ContextKey added in v3.2.0

type ContextKey string

ContextKey is used for context.Context value. The value requires a key that is not primitive type.

const ContextKeyRequestID ContextKey = "requestID"

ContextKeyRequestID is the ContextKey for RequestID

type ErrorHandled

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

ErrorHandled implement the IErrorHandled interface

func NewBadRequest

func NewBadRequest(content interface{}) ErrorHandled

NewBadRequest produce an ErrorHandled with the status code 400

func NewConflict

func NewConflict(content interface{}) ErrorHandled

NewConflict produce an ErrorHandled with the status code 409

func NewErrorHandled

func NewErrorHandled(op int, content interface{}) ErrorHandled

NewError return a new ErrorHandled var

func NewInternal

func NewInternal(content interface{}) ErrorHandled

NewUnprocessable produce an ErrorHandled with the status code 500

func NewNoContent

func NewNoContent() ErrorHandled

NewNoContent produce an ErrorHandled with the status code 204

func NewNotAcceptable

func NewNotAcceptable(content interface{}) ErrorHandled

NewNotAcceptable produce an ErrorHandled with the status code 406

func NewNotFound

func NewNotFound(content interface{}) ErrorHandled

NewNotAcceptable produce an ErrorHandled with the status code 404

func NewNotImplemented

func NewNotImplemented(content interface{}) ErrorHandled

NewUnprocessable produce an ErrorHandled with the status code 501

func NewProcessing

func NewProcessing(content interface{}) ErrorHandled

NewProcessing produce an ErrorHandled with the status code 102

func NewServiceUnavailable added in v3.2.0

func NewServiceUnavailable(content interface{}) ErrorHandled

NewServiceUnavailable produce an ErrorHandled with the status code 422

func NewUnauthorized

func NewUnauthorized(content interface{}) ErrorHandled

NewUnauthorized produce an ErrorHandled with the status code 401

func NewUnprocessable

func NewUnprocessable(content interface{}) ErrorHandled

NewUnprocessable produce an ErrorHandled with the status code 422

func (ErrorHandled) Error

func (e ErrorHandled) Error() string

Error implement the error interface

func (ErrorHandled) GetContent

func (e ErrorHandled) GetContent() interface{}

GetContent implement the IErrorHandled interface

func (ErrorHandled) GetOPCode

func (e ErrorHandled) GetOPCode() int

GetOPCode implement the IErrorHandled interface

func (ErrorHandled) SetWrapped

func (e ErrorHandled) SetWrapped(err error) IErrorHandled

func (ErrorHandled) Unwrap

func (e ErrorHandled) Unwrap() error

type HandlerSign

type HandlerSign func(c IContext)

HandlerSign hold the signature of the controller

type IContext

type IContext interface {
	GetRequestID() string
	SetRequestID(id string) IContext

	// GetRequest return the holded http.Request object
	GetRequest() *http.Request

	// SetRequest is used to save the request object
	SetRequest(rq *http.Request) IContext

	// SetWriter is used to save the ResponseWriter obj
	SetWriter(rw http.ResponseWriter) IContext

	// SetVars is used to save the url vars
	SetVars(vars map[string]string) IContext

	// GetVar return the url var parameters. Empty string for none
	GetVar(key string) (val string)

	// SetQuery save the query param object
	SetQuery(query map[string][]string) IContext

	// GetQueries return the queries object
	GetQueries() map[string][]string

	// GetQuery fetch the query object key
	GetQuery(key string) (val string, ok bool)

	// SetLogger set the logger of the ctx
	SetLogger(logger log.ILog) IContext

	// Save the given context object into the fmwk context
	SetContext(ctx context.Context) IContext

	// Fetch the previously saved context object
	GetContext() context.Context

	// FetchContent extract the content from the body
	FetchContent(content interface{})

	// Validate is used to validate a content of the content params
	Validate(content interface{})

	// Decode load the query param in the content object
	DecodeQP(content interface{})

	// IsPretty toggle the compact outptu mode
	IsPretty() bool

	// CheckHeader ensure the Content-Type of the request
	CheckHeader()

	// OwnRecover is used to encapsulate the wanted panic
	OwnRecover()

	// SendResponse create & send a response according to the parameters
	SendResponse(op int, content []byte, headers ...[2]string)

	// JSONBlob answer the JSON content with the status code op
	JSONBlob(op int, content []byte)

	// JSON answer the JSON content with the status code op
	JSON(op int, content interface{})

	// 200
	JSONOk(interface{})

	// 201
	JSONCreated(interface{})

	// 202
	JSONAccepted(interface{})

	//
	JSONNotImplemented(interface{})

	//
	JSONNoContent()

	//
	JSONBadRequest(interface{})

	//
	JSONUnprocessable(interface{})

	// 404
	JSONNotFound(interface{})

	//
	JSONConflict(interface{})

	// 500
	JSONInternalError(interface{})
}

IContext Interface implement the context used in this project

type IErrorHandled

type IErrorHandled interface {
	// error
	Error() string
	Unwrap() error
	GetOPCode() int
	GetContent() interface{}
	SetWrapped(err error) IErrorHandled
}

IErrorHandled interface implement the panic recovering

type Option added in v3.2.0

type Option func(s *Server)

Option is tu be used this way :

  s := w.InitServer(
    webfmwk.EnableCheckIsUp()
    webfmwk.WithCORS(),
    webfmwk.WithLogger(log.GetLogger()),
    webfmwk.WithMiddlewars(
	    middleware.Logging,
	    middleware.Security))

func CheckIsUp added in v3.2.0

func CheckIsUp() Option

func SetMaxHeaderBytes added in v3.2.0

func SetMaxHeaderBytes(val int) Option

func SetPrefix added in v3.2.0

func SetPrefix(prefix string) Option

func SetReadHeaderTimeout added in v3.2.0

func SetReadHeaderTimeout(val time.Duration) Option

func SetReadTimeout added in v3.2.0

func SetReadTimeout(val time.Duration) Option

ReadTimeout is a timing constraint on the client http request imposed by the server from the moment of initial connection up to the time the entire request body has been read.

[Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]

func SetWriteTimeout added in v3.2.0

func SetWriteTimeout(val time.Duration) Option

WriteTimeout is a time limit imposed on client connecting to the server via http from the time the server has completed reading the request header up to the time it has finished writing the response.

[Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]

func WithCORS added in v3.2.0

func WithCORS() Option

func WithCtrlC added in v3.2.0

func WithCtrlC() Option

func WithCustomContext added in v3.2.0

func WithCustomContext(setter Setter) Option

func WithDocHandler added in v3.2.0

func WithDocHandler(handler http.Handler) Option

func WithLogger added in v3.2.0

func WithLogger(lg log.ILog) Option

func WithMiddlewars added in v3.2.0

func WithMiddlewars(mw ...mux.MiddlewareFunc) Option

type Route

type Route struct {
	Verbe   string      `json:"verbe"`
	Path    string      `json:"path"`
	Name    string      `json:"name"`
	Handler HandlerSign `json:"-"`
}

Route hold the data for one route

type Routes

type Routes []Route

Routes hold an array of route

type RoutesPerPrefix

type RoutesPerPrefix map[string]Routes

RoutesPerPrefix hold the routes and there respectiv prefix

type Server

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

Server is a struct holding all the necessary data / struct

func InitServer

func InitServer(opts ...Option) *Server

func (*Server) AddRoute

func (s *Server) AddRoute(r Route)

AddRoute add a new route to expose

func (*Server) AddRoutes

func (s *Server) AddRoutes(r Routes)

AddRoutes save all the routes to expose

func (*Server) DELETE

func (s *Server) DELETE(path string, handler HandlerSign)

DELETE expose a route to the http verb DELETE

func (*Server) DumpRoutes added in v3.2.0

func (s *Server) DumpRoutes()

DumpRoutes dump the API endpoints using the server logger

func (*Server) EnableCORS added in v3.2.0

func (s *Server) EnableCORS() *Server

EnableCORS enable CORS verification

func (*Server) EnableCheckIsUp added in v3.2.0

func (s *Server) EnableCheckIsUp() *Server

EnableCheckIsUp add an /ping endpoint. Is used, cnce a server is started, the user can check weather the server is up or not by reading the isReady channel vie the IsReady() method

func (*Server) EnableCtrlC added in v3.2.0

func (s *Server) EnableCtrlC() *Server

EnableCtrlC let the server handle the SIGINT interuption. To add worker to the interuption pool, please use the `GetLauncher` method

func (*Server) GET

func (s *Server) GET(path string, handler HandlerSign)

GET expose a route to the http verb GET

func (*Server) GetContext

func (s *Server) GetContext() context.Context

GetContext return the context.Context used

func (*Server) GetLauncher

func (s *Server) GetLauncher() *WorkerLauncher

GetLauncher return a pointer to the internal workerLauncher

func (*Server) GetLogger

func (s *Server) GetLogger() log.ILog

GetLogger return the used ILog instance

func (*Server) IsReady added in v3.2.0

func (s *Server) IsReady() chan bool

IsReady return the channel on which `true` is send once the server is up

func (*Server) PATCH

func (s *Server) PATCH(path string, handler HandlerSign)

PATCH expose a route to the http verb PATCH

func (*Server) POST

func (s *Server) POST(path string, handler HandlerSign)

POST expose a route to the http verb POST

func (*Server) PUT

func (s *Server) PUT(path string, handler HandlerSign)

PUT expose a route to the http verb PUT

func (*Server) RegisterDocHandler

func (s *Server) RegisterDocHandler(handler http.Handler) *Server

RegisterDocHandler is used to register an swagger doc handler

func (*Server) RegisterLogger added in v3.2.0

func (s *Server) RegisterLogger(lg log.ILog) *Server

RegisterLogger register the ILog used

func (*Server) RegisterMiddlewares added in v3.2.0

func (s *Server) RegisterMiddlewares(mw ...mux.MiddlewareFunc) *Server

RegisterMiddlewares register the middlewares arguments

func (*Server) RouteApplier

func (s *Server) RouteApplier(rpp RoutesPerPrefix)

RouteApplier apply the array of RoutePerPrefix

func (*Server) SetCustomContext

func (s *Server) SetCustomContext(setter Setter) *Server

SetCustomContext save a custom context so it can be fetched in the controllers

func (*Server) SetPrefix

func (s *Server) SetPrefix(prefix string)

SetPrefix set the url path to prefix

func (*Server) SetRouter

func (s *Server) SetRouter() *mux.Router

SetRouter create a mux.Handler router and then : register the middle wares, register the user defined routes per prefix, and return the routes handler

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context)

Shutdown call the framework shutdown to stop all running server

func (*Server) Start

func (s *Server) Start(addr string)

Start expose an server to an HTTP endpoint

func (*Server) StartTLS

func (s *Server) StartTLS(addr string, tlsStuffs TLSConfig)

StartTLS expose an server to an HTTPS endpoint

func (*Server) WaitAndStop

func (s *Server) WaitAndStop()

WaitAndStop wait for all servers to terminate. Use of a sync.waitGroup to properly wait all running servers.

type ServerMeta added in v3.2.0

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

type Setter added in v3.2.0

type Setter func(c *Context) IContext

type TLSConfig

type TLSConfig struct {
	Cert     string `json:"cert"`
	Key      string `json:"key"`
	Insecure bool   `json:"insecure"`
}

TLSConfig contain the tls config passed by the config file

type ValidationError

type ValidationError struct {
	Error validator.ValidationErrorsTranslations `json:"error"`
}

Context implement the IContext interface It hold the data used by the request

type WorkerLauncher

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

WorkerLauncher hold the different workers

func CreateWorkerLauncher

func CreateWorkerLauncher(wg *sync.WaitGroup, cancel context.CancelFunc) WorkerLauncher

to use as a factory as the fields are unexported

func (*WorkerLauncher) Start

func (l *WorkerLauncher) Start(name string, fn func() error)

launch a worker who will be wait & kill at the same time than the others

Directories

Path Synopsis
package log implement the ILog interface used by the webfmwk
package log implement the ILog interface used by the webfmwk
Package middleware implement some basic middleware for the webfmwk middleware provides a convenient mechanism for filtering HTTP requests entering the application.
Package middleware implement some basic middleware for the webfmwk middleware provides a convenient mechanism for filtering HTTP requests entering the application.
Package testing hold some testing method used for both assertion and testing the webfmwk
Package testing hold some testing method used for both assertion and testing the webfmwk

Jump to

Keyboard shortcuts

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