otto

package module
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2018 License: MIT Imports: 18 Imported by: 0

README

Otto

GoDoc Build Status Go Report Card

Otto is an easy way to use HTTP in golang. You can either use the Otto App with features like gracefully shutdown on OS signals interrupt and kill, or just use the Otto Router and handle the HTTP Server as you like!

Otto uses Gorilla/mux to define routes.

Feature overview

  • Group APIs
  • Middleware
  • Functions that makes it easy to send HTTP responses
  • Centralized HTTP error handling
  • Custom error handlers to specific HTTP status codes
  • Possibility to only use the router part
  • A easy way to decode the request body (only json for now, other formats will come later)
  • Automatic TLS via Let’s Encrypt

Examples

Example of how to use the Otto App

package main

import (
  "log"
  "github.com/JacobSoderblom/otto"
)

func main() {
  opts := otto.NewOptions()
  opts.Addr = ":3000"

  app := otto.New(opts)

  app.GET("/", func(ctx otto.Context) error {
    return ctx.String(200, "Hello world!")
  })

  log.Fatal(app.Serve())
}

Example of how to use Otto with TLS

package main

import (
  "log"
  "github.com/JacobSoderblom/otto"
)

func main() {
  opts := otto.NewOptions()
  opts.Addr = ":443"

  app := otto.New(opts)

  if err := app.UseTLS("path/to/cert", "path/to/key"); err != nil {
    log.Fatal(err)
  }

  app.GET("/", func(ctx otto.Context) error {
    return ctx.String(200, "Hello world!")
  })

  log.Fatal(app.Serve())
}

Example of how to use Otto with Auto TLS from Let’s Encrypt

package main

import (
  "log"
  "github.com/JacobSoderblom/otto"
)

func main() {
  opts := otto.NewOptions()
  opts.Addr = ":443"

  app := otto.New(opts)

  app.UseAutoTLS(autocert.DirCache("/path/to/cache"))

  app.GET("/", func(ctx otto.Context) error {
    return ctx.String(200, "Hello world!")
  })

  log.Fatal(app.Serve())
}

Example of how to use the Router without the Otto App.

The Router implements the http.Handler so it is easy to use without the App!

package main

import (
  "log"
  "github.com/JacobSoderblom/otto"
)

func main() {
  r := otto.NewRouter(false)

  r.GET("/", func(ctx otto.Context) error {
    return ctx.String(200, "Hello world!")
  })

  log.Fatal(http.ListenAndServe(":3000", r))
}

Example of using middlewares

package main

import (
  "log"
  "github.com/JacobSoderblom/otto"
)

func main() {
  r := otto.NewRouter(false)

  r.Use(func(next otto.HandlerFunc) otto.HandlerFunc {
    return func(ctx otto.Context) error {
      ctx.Set("some key", "I'm a middleware!")
      return next(ctx)
    }
  })

  r.GET("/", func(ctx otto.Context) error {
    return ctx.String(200, "Hello world!")
  })

  log.Fatal(http.ListenAndServe(":3000", r))
}

Example of how to associate error handler to HTTP status code

package main

import (
  "log"
  "github.com/JacobSoderblom/otto"
)

func main() {
  r := otto.NewRouter(false)

  errorHandlers := map[int]otto.ErrorHandler{
    400: func(code int, err error, ctx otto.Context) error {
      // do some awesome error handling!
      return ctx.Error(code, err)
    },
    401: func(code int, err error, ctx otto.Context) error {
      // do some awesome error handling!
      return ctx.Error(code, err)
    },
  }

  r.SetErrorHandlers(errorHandlers)

  r.GET("/", func(ctx otto.Context) error {
    return ctx.String(400, "Hello world!")
  })

  log.Fatal(http.ListenAndServe(":3000", r))
}

Example of how to decode the request body

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/JacobSoderblom/otto"
)

func main() {
	r := otto.NewRouter(false)

	r.POST("/", func(ctx otto.Context) error {
		var body struct {
			Msg string `json:"msg"`
		}

		if err := ctx.Bind(&body); err != nil {
			return err
		}

		return ctx.JSON(200, body)
	})

	log.Fatal(http.ListenAndServe(":3000", r))
}

Documentation

Index

Constants

View Source
const (
	HeaderAccept                        = "Accept"
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAllow                         = "Allow"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXForwardedProtocol            = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                 = "X-Forwarded-Ssl"
	HeaderXUrlScheme                    = "X-Url-Scheme"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderXRequestID                    = "X-Request-ID"
	HeaderXRequestedWith                = "X-Requested-With"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderStrictTransportSecurity       = "Strict-Transport-Security"
	HeaderXContentTypeOptions           = "X-Content-Type-Options"
	HeaderXXSSProtection                = "X-XSS-Protection"
	HeaderXFrameOptions                 = "X-Frame-Options"
	HeaderContentSecurityPolicy         = "Content-Security-Policy"
)

Headers for HTTP

View Source
const (
	MIMEMultipartForm   = "multipart/form-data"
	MIMEApplicationForm = "application/x-www-form-urlencoded"
	MIMEApplicationJSON = "application/json"
)

Mime types

Variables

This section is empty.

Functions

func DefaultBinder added in v0.1.4

func DefaultBinder(ctx Context, dest interface{}) error

DefaultBinder checks Content Type from request and tries to decode the body with appropriate decoder

func DefaultErrorHandler

func DefaultErrorHandler(code int, err error, ctx Context) error

DefaultErrorHandler will return the error as json

Types

type App

type App struct {
	*Router
	// contains filtered or unexported fields
}

App holds on to options and the underlying router, the middleware, and more

func New

func New(opts Options) *App

New creates a new App

func (*App) Close

func (a *App) Close(err error) error

Close the application and try to shutdown gracefully

func (*App) Serve

func (a *App) Serve() error

Serve serves the application at the specified address and listening to OS interrupt and kill signals and will try to shutdown the app gracefully

func (*App) UseAutoTLS added in v0.1.10

func (a *App) UseAutoTLS(cache autocert.DirCache)

UseAutoTLS will setup autocert.Manager and request cert from https://letsencrypt.org

func (*App) UseTLS added in v0.1.10

func (a *App) UseTLS(certFile, keyFile string) error

UseTLS will use tls.LoadX509KeyPair to setup certificate for TLS

type BindFunc added in v0.1.4

type BindFunc func(Context, interface{}) error

BindFunc defines func to run bind

type Context

type Context interface {
	JSON(int, interface{}) error
	HTML(int, string) error
	String(int, string) error
	Error(int, error) error
	NoContent() error
	Redirect(code int, location string) error
	Request() *http.Request
	Response() *Response
	FormParams() (*ValueParams, error)
	QueryParams() *ValueParams
	QueryString() string
	Bind(interface{}) error
	Params() Params
	Set(key string, val interface{})
	Get(key string) interface{}
}

Context defines interface for otto Context

type ErrorHandler

type ErrorHandler func(int, error, Context) error

ErrorHandler defines the interface of a error handler

type ErrorHandlers

type ErrorHandlers struct {
	DefaultHandler ErrorHandler
	Handlers       map[int]ErrorHandler
}

ErrorHandlers holds a list of ErrorHandlers associated to status codes. It also holds a default ErrorHandler that will kick in if there is no other ErrorHandlers

func (ErrorHandlers) Copy added in v0.1.7

func (e ErrorHandlers) Copy() ErrorHandlers

Copy creates a copy of the ErrorHandlers struct

func (ErrorHandlers) Get

func (e ErrorHandlers) Get(code int) ErrorHandler

Get will return a ErrorHandler that is associated with the provided status code, if none was found the DefaultHandler will be returned

type HTTPError

type HTTPError struct {
	Code int
	Err  error
}

HTTPError a typed error returned by handlers

func (HTTPError) Error

func (e HTTPError) Error() string

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc defines the interface for r Route HandlerFunc

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware defines the inteface for a otto Middleware

type Options

type Options struct {
	Addr              string
	StrictSlash       bool
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	MaxHeaderBytes    int

	DisableHTTP2 bool
	// contains filtered or unexported fields
}

Options has all options that can be passed to App

func NewOptions

func NewOptions() Options

NewOptions creates new Options with default values

type Params added in v0.1.5

type Params map[string]string

Params holds url params and provides simple ways to parse the value to different types

func (Params) Bool added in v0.1.5

func (p Params) Bool(key string) (bool, error)

Bool returns the value as bool

func (Params) Int added in v0.1.5

func (p Params) Int(key string) (int, error)

Int returns the value as int

func (Params) String added in v0.1.5

func (p Params) String(key string) string

String returns the value as string

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Response that holds some information about the response

func (Response) Size

func (r Response) Size() int

Size returns the size of the content

func (*Response) Write

func (r *Response) Write(b []byte) (int, error)

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader writes the code to response writer and stores the status code

type Route

type Route struct {
	Path        string
	Method      string
	HandlerFunc HandlerFunc
	// contains filtered or unexported fields
}

Route has information about the route

func (Route) ServeHTTP

func (r Route) ServeHTTP(res http.ResponseWriter, req *http.Request)

type Router

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

Router handles all middleware, routes and error handlers

func NewRouter

func NewRouter(strictSlash bool) *Router

NewRouter creates a new Router with some default values

func (*Router) DELETE

func (r *Router) DELETE(p string, h HandlerFunc)

DELETE maps an "DELETE" request to the path and handler

func (*Router) GET

func (r *Router) GET(p string, h HandlerFunc)

GET maps an "GET" request to the path and handler

func (*Router) Group

func (r *Router) Group(p string) *Router

Group creates a new Router with a prefix for all routes

func (*Router) HEAD

func (r *Router) HEAD(p string, h HandlerFunc)

HEAD maps an "HEAD" request to the path and handler

func (*Router) OPTIONS

func (r *Router) OPTIONS(p string, h HandlerFunc)

OPTIONS maps an "OPTIONS" request to the path and handler

func (*Router) PATCH

func (r *Router) PATCH(p string, h HandlerFunc)

PATCH maps an "PATCH" request to the path and handler

func (*Router) POST

func (r *Router) POST(p string, h HandlerFunc)

POST maps an "POST" request to the path and handler

func (*Router) PUT

func (r *Router) PUT(p string, h HandlerFunc)

PUT maps an "PUT" request to the path and handler

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)

func (*Router) SetErrorHandlers

func (r *Router) SetErrorHandlers(eh map[int]ErrorHandler)

SetErrorHandlers associate error handlers with a status code

func (*Router) Static

func (r *Router) Static(p string, fs http.FileSystem)

Static serves static files like javascript, css and html files

func (*Router) Use

func (r *Router) Use(mf ...Middleware)

Use adds a Middleware to the router

type Routes

type Routes []*Route

Routes alias for slice of routes

func (Routes) Len

func (r Routes) Len() int

func (Routes) Less

func (r Routes) Less(i, j int) bool

func (Routes) Swap

func (r Routes) Swap(i, j int)

type Store added in v0.1.8

type Store map[string]interface{}

Store is a generic map

type ValueParams added in v0.1.5

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

ValueParams holds url.Values and provides simple ways to parse the value to different types

func (ValueParams) Bool added in v0.1.5

func (p ValueParams) Bool(key string) (bool, error)

Bool gets one value associated with key and returns it as bool

func (ValueParams) Bools added in v0.1.5

func (p ValueParams) Bools(key string) ([]bool, error)

Bools returns all value associated with key as bool slice

func (ValueParams) Int added in v0.1.5

func (p ValueParams) Int(key string) (int, error)

Int gets one value associated with key and returns it as int

func (ValueParams) Ints added in v0.1.5

func (p ValueParams) Ints(key string) ([]int, error)

Ints returns all value associated with key as int slice

func (ValueParams) String added in v0.1.5

func (p ValueParams) String(key string) string

String gets one value associated with key and returns it as string

func (ValueParams) Strings added in v0.1.5

func (p ValueParams) Strings(key string) []string

Strings returns all value associated with key as string slice

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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