gwf

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2020 License: MIT Imports: 20 Imported by: 1

README

gwf

Build codecov Go Report Card

A web framework for Go with simple APIs to use. It solves common problems of a web server so engineers can focus on business logic.

Features

  • Graceful shutdown
  • Panic recovery
  • CORS
  • Gzip compression

Quick Start

Installation
go get github.com/bongnv/gwf
Example
package main

import (
	"context"
	"log"

	"github.com/bongnv/gwf"
)

func main() {
    app := gwf.Default()
    app.GET("/hello-world", func(ctx context.Context, req gwf.Request) (interface{}, error) {
        return "OK", nil
    })
    log.Println(app.Run())
}

Usages

Options

An Option customizes an Application and these are available Option:

WithLogger

WithLogger allows to specify a custom implementation of the logger.

  logger := log.New(os.Stderr, "", log.LstdFlags)
  app := gwf.New(gwf.WithLogger(logger))
Route Options

A RouteOption customizes a route. It can be used to add middlewares like Recovery().

For convenience, a RouteOption can be a Option for the Application. In this case, the RouteOption will be applied to all routes.

WithRecovery

WithRecovery recovers from panics and returns error with 500 status code to clients.

    app.GET("/hello-world", helloWorld, gwf.WithRecovery())
WithDecoder

WithDecoder specifies a custom logic for decoding the request to a request DTO.

   app.GET("/hello-world", helloWorld, gwf.WithDecoder(customDecoder))
WithCORS

WithCORS enables the support for Cross-Origin Resource Sharing. Ref: https://developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS.

  app := gwf.New(gwf.WithCORS(gwf.DefaultCORSConfig))
  // or
  app.GET("/hello-world", helloWorld, gwf.WithCORS(gwf.DefaultCORSConfig))
WithErrorHandler

WithErrorHandler allows to specify a custom ErrorHandler which converts an error into HTTP response.

func yourCustomErrHandler(w http.ResponseWriter, errResp error) {
    w.WriteHeader(http.StatusInternalServerError)
    if err := encoder.Encode(w, errResp); err != nil {
        logger.Println("Error", err, "while encoding", errResp)
    }
}

func yourInitFunc(app *gwf.Application) {
    app.GET("/hello-world", helloWorld, gwf.WithErrorHandler(yourCustomErrHandler))
}
Grouping routes

gwf supports grouping routes which share the same prefix or options for better readability.

func main() {
    app := gwf.Default()

    // v1 group
    v1 := app.Group("/v1", WithV1Option())
    v1.GET("/hello-world", helloWorldV1)

    // v2 group
    v2 := app.Group("/v2", WithV2Option())
    v2.GET("/hello-world", helloWorldV2)

    log.Println(app.Run())
}

Documentation

Index

Constants

View Source
const (
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderOrigin                        = "Origin"
	HeaderVary                          = "Vary"
)

Headers

Variables

View Source
var DefaultCORSConfig = CORSConfig{
	AllowOrigins: []string{"*"},
	AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
}

DefaultCORSConfig is the default configuration for the WithCORS middleware.

View Source
var (
	// DefaultGzipConfig is the default config for Gzip middleware.
	DefaultGzipConfig = GzipConfig{
		Level: gzip.DefaultCompression,
	}
)

Functions

func ResponseHeaderFromCtx

func ResponseHeaderFromCtx(ctx context.Context) http.Header

ResponseHeaderFromCtx returns Header for HTTP response which will be sent. The function returns a nil map if the Header doesn't exist.

Types

type Application

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

Application is a web application.

func Default

func Default() *Application

Default returns an Application with a default set of configurations.

func New

func New(opts ...Option) *Application

New creates a new application.

func (*Application) DELETE

func (app *Application) DELETE(path string, h Handler, opts ...RouteOption)

DELETE registers a new DELETE route for a path with handler.

func (*Application) GET

func (app *Application) GET(path string, h Handler, opts ...RouteOption)

GET registers a new GET route for a path with handler.

func (*Application) Group

func (app *Application) Group(prefix string, opts ...RouteOption) *Group

Group creates a group of sub-routes

func (*Application) PATCH

func (app *Application) PATCH(path string, h Handler, opts ...RouteOption)

PATCH registers a new PATCH route for a path with handler.

func (*Application) POST

func (app *Application) POST(path string, h Handler, opts ...RouteOption)

POST registers a new POST route for a path with handler.

func (*Application) PUT

func (app *Application) PUT(path string, h Handler, opts ...RouteOption)

PUT registers a new PUT route for a path with handler.

func (*Application) Run

func (app *Application) Run() error

Run starts an HTTP server.

type CORSConfig

type CORSConfig struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	AllowCredentials bool
	MaxAge           int
}

CORSConfig defines the config for WithCORS middleware.

type CustomHTTPResponse

type CustomHTTPResponse interface {
	WriteTo(w http.ResponseWriter)
}

CustomHTTPResponse defines an interface to support custom HTTP response.

type Decoder

type Decoder interface {
	// Decode decodes a request to a struct. req.PostForm is called in advanced.
	Decode(obj interface{}, req *http.Request) error
}

Decoder defines a request decoder.

type Encoder

type Encoder interface {
	// Encode encodes obj and writes to http.ResponseWriter.
	Encode(w http.ResponseWriter, obj interface{}) error
}

Encoder define a request decoder.

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, err error)

ErrorHandler defines a handler which handles error.

type Group

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

Group is a group of sub-routes. It can be used for a group of routes which share same middlewares.

func (*Group) DELETE

func (g *Group) DELETE(path string, h Handler, opts ...RouteOption)

DELETE registers a new DELETE route for a path with handler.

func (*Group) GET

func (g *Group) GET(path string, h Handler, opts ...RouteOption)

GET registers a new GET route for a path with handler.

func (*Group) PATCH

func (g *Group) PATCH(path string, h Handler, opts ...RouteOption)

PATCH registers a new PATCH route for a path with handler.

func (*Group) POST

func (g *Group) POST(path string, h Handler, opts ...RouteOption)

POST registers a new POST route for a path with handler.

func (*Group) PUT

func (g *Group) PUT(path string, h Handler, opts ...RouteOption)

PUT registers a new PUT route for a path with handler.

type GzipConfig

type GzipConfig struct {
	// Gzip compression level.
	// Optional. Default value -1.
	Level int
}

GzipConfig defines the config for Gzip middleware.

type HTTPError

type HTTPError struct {
	Code    int    `json:"-"`
	Message string `json:"message"`
}

HTTPError is a simple implementation of HTTP Error.

func (*HTTPError) Error

func (err *HTTPError) Error() string

Error implements error interface.

func (*HTTPError) WriteTo added in v0.3.0

func (err *HTTPError) WriteTo(w http.ResponseWriter)

WriteTo implements CustomHTTPResponse. It encodes the response as JSON format.

type Handler

type Handler func(ctx context.Context, req Request) (interface{}, error)

Handler defines a function to serve HTTP requests.

type Logger

type Logger interface {
	// Println prints out logs like fmt.Println.
	Println(...interface{})
}

Logger defines a Logger.

type Middleware

type Middleware func(Handler) Handler

Middleware defines a middleware to provide additional logic.

func WithCORS

func WithCORS(cfg CORSConfig) Middleware

WithCORS returns a middleware to support Cross-Origin Resource Sharing.

func (Middleware) Apply

func (m Middleware) Apply(app *Application)

Apply implements Option.

func (Middleware) ApplyRoute

func (m Middleware) ApplyRoute(r *route)

ApplyRoute implements RouteOption.

type Option

type Option interface {
	Apply(app *Application)
}

Option defines an application Option.

type OptionFn

type OptionFn func(app *Application)

OptionFn defines a function that implements Option

func WithLogger

func WithLogger(l Logger) OptionFn

WithLogger specifies a custom Logger for tha application.

func (OptionFn) Apply

func (opt OptionFn) Apply(app *Application)

Apply implements Option.

type Request

type Request interface {
	// HTTPRequest returns the http.Request.
	HTTPRequest() *http.Request
	// Decode decodes the request to an object.
	Decode(obj interface{}) error
}

Request defines a HTTP request.

type RouteOption

type RouteOption interface {
	ApplyRoute(r *route)
}

RouteOption defines an option to customize a route.

type RouteOptionFn

type RouteOptionFn func(r *route)

RouteOptionFn defines a function implementation of RouteOption.

func WithDecoder

func WithDecoder(d Decoder) RouteOptionFn

WithDecoder specifies the decoder which will be used.

func WithEncoder

func WithEncoder(e Encoder) RouteOptionFn

WithEncoder specifies the encoder which will be used to encode payload to HTTP response.

func WithErrorHandler

func WithErrorHandler(errHandler ErrorHandler) RouteOptionFn

WithErrorHandler is a RouteOption to specify a custom ErrorHandler.

func WithGzip

func WithGzip(cfg GzipConfig) RouteOptionFn

WithGzip returns a middleware which compresses HTTP response using gzip compression.

func WithRecovery

func WithRecovery() RouteOptionFn

WithRecovery returns a middleware which recovers from panics.

func (RouteOptionFn) Apply

func (fn RouteOptionFn) Apply(app *Application)

Apply implements Option.

func (RouteOptionFn) ApplyRoute

func (fn RouteOptionFn) ApplyRoute(r *route)

ApplyRoute implements RouteOption.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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