web

package module
v0.0.0-...-11af2ba Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2021 License: MIT Imports: 16 Imported by: 0

README

web

PkgGoDev Tests

Yet another minimal and personal DIY web framework for golang.

Goals

  • Security

      Safe by default, using documented best practices
    
  • Minimalism

      Cherry-picking of features, avoiding 3rd party dependecies
    
  • Sane Defaults

      Minimal configuration required, good performance without ugly hacks
    

Status

Under development.

License

MIT licensed. See the LICENSE file for details.

References

Security
  • General web security recommendations (feels up to date, lot's of http headers available)

      https://almanac.httparchive.org/en/2020/security
      https://owasp.org/www-project-secure-headers/
    
  • Go web server recommendations (somewhat out of date?)

      https://blog.cloudflare.com/exposing-go-on-the-internet/
      https://juliensalinas.com/en/security-golang-website/
    
  • TLS best practices (and with a good config generator)

      https://wiki.mozilla.org/Security/Server_Side_TLS
      https://www.ssllabs.com/ssl-pulse/
    
  • Go's TLS defaults (cipher suits etc.)

      https://go.googlesource.com/go/+blame/go1.15.6/src/crypto/tls/common.go
    
  • Checking for issues in the source code

      https://github.com/golang/lint
      https://github.com/securego/gosec
    

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidTemplate = errors.New("invalid template")

ErrInvalidTemplate is returned when you try to render a template with an unknown name.

Functions

func LoadTemplates

func LoadTemplates(globDir string, funcs template.FuncMap) map[string]*template.Template

LoadTemplates is a helper for quickly loading template files from a dir (using a filepath.Glob pattern) and an optional FuncMap. The returned map can be used straight away in the Options{} struct for the web handler. Templates are sorted (and parsed) by their file names.

NOTE: it will cause a panic on any errors (cuz I think it's bad enough, while trying to start up the web server).

TODO: rewrite this helper to use embed.FS instead, after go1.16 has landed in feb 2021

(see https://tip.golang.org/pkg/embed/)

func LoadTemplatesWithLayout

func LoadTemplatesWithLayout(globDir string, funcs template.FuncMap) map[string]*template.Template

LoadTemplatesWithLayout works basicly in the same way as LoadTemplates, except (!) the first template will be used as the base layout for the other templates.

NOTE: the layout template will be unavailable to render stand alone

func NewServer

func NewServer(opt *ServerOptions) *http.Server

NewServer creates and sets up a new http.Server, using safe settings that should make it safer to expose to the internet. Settings are sourced from better informed security people and their published works :)

func SimpleErrorHandler

func SimpleErrorHandler(c *Context, err error) error

SimpleErrorHandler is the default handler for handling handler errors (that sounded sick). It checks if an error is a Error and sends it's status code and msg as the http response. If it's not, it simply sends an "500 internal server error" for all other errors.

func SimpleNotFoundHandler

func SimpleNotFoundHandler(c *Context) error

SimpleNotFoundHandler is the default "404 not found" handler. It simply calls http.NotFound()

Types

type Context

type Context struct {
	M *Mux

	W http.ResponseWriter
	R *http.Request
	P httprouter.Params
}

Context is a convenience struct for easing the handling of a http request.

func (*Context) Bytes

func (c *Context) Bytes(status int, data []byte) error

Bytes is a quick helper to send a response, with the contents of []byte{} as body. You should set a Content-Type header yourself.

func (*Context) DecodeJSON

func (c *Context) DecodeJSON(data interface{}) error

DecodeJSON is a helper for JSON decoding a request body.

func (*Context) Empty

func (c *Context) Empty(status int) error

Empty let's you send a response code with empty body.

func (*Context) Error

func (c *Context) Error(status int, msg string) error

Error returns an *Error to the client, with http response "status" and "msg" body.

func (*Context) File

func (c *Context) File(fs http.FileSystem, fp string) error

File attemps to send the contents of a file, located at `fp` and opened using `fs`. Default behaviour: * File path will be cleaned and resolved * Dotfiles will be ignored (or not, optionally) * Directory listnings will be ignored (or optionally serve an index file instead) * Any paths ignored will serve a `NotFound()` response instead * Content-Type will be autodetected (see `http.ServeContent` for more info and other extra handling)

Warning: if http.Server timeouts are set too short, this write might time out. TODO: replace http.FileSystem with io/fs.FS when go1.16 lands

func (*Context) GetHeader

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

GetHeader is a shortcut to get a header value from a request.

func (*Context) GetParams

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

GetParams is a shortcut to get URL params, first one given by key. See https://pkg.go.dev/github.com/julienschmidt/httprouter#Param for more info. It's safe to call when *Context.P == nil

func (*Context) HTML

func (c *Context) HTML(status int, data string) error

HTML is a helper to send a simple HTML body, with a 'text/html' Content-Type header.

func (*Context) JSON

func (c *Context) JSON(status int, data interface{}) error

JSON is a helper for JSON encoding the data and sending it with a response status.

func (*Context) Log

func (c *Context) Log(msg string, args ...interface{})

Log logs a message and args, if a logger is available.

func (*Context) NotFound

func (c *Context) NotFound() error

NotFound returns the result from the '404 not found' handler set at setup.

func (*Context) Redirect

func (c *Context) Redirect(status int, url string) error

Redirect sends a redirection response. It also makes sure the response code is within range.

func (*Context) Render

func (c *Context) Render(status int, tmpl string, data interface{}) error

Render tries to render a HTML template (using tmpl as key for the Options.Template map, from the handler). Optional data can be provided for the template.

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader is a shortcut to set a header value for a response.

func (*Context) Stream

func (c *Context) Stream(status int, r io.Reader) error

Stream tries to stream the contents of an 'io.Reader'. No Content-Type is auto detected, so you should set it yourself. Warning: if http.Server timeouts are set too short, this write might time out.

func (*Context) String

func (c *Context) String(status int, data string) error

String is a helper to send a simple string body, with a 'text/plain' Content-Type header.

type Error

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

Error is a custom error which also contains a http status code. Whenever a Handler returns this error, the error message and status code will be sent back to the client unaltered.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Status

func (e *Error) Status() int

Status returns the HTTP status code for this error.

type ErrorHandler

type ErrorHandler func(*Context, error) error

ErrorHandler is a sort of a Handler, but it also takes an error.

type Handler

type Handler func(*Context) error

Handler is a shorter convenience function signature for http handlers, instead of func(http.ResponseWriter, *http.Request). It also allows for easier error handling.

type Middleware

type Middleware func(Handler) Handler

Middleware is a function signature used when wrapping a Handler in one or many Handler middlewares.

type Mux

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

Mux implements the http.Handler interface and allows you to easily register handlers and middleware with sane defaults. It uses github.com/julienschmidt/httprouter, for quick and easy routing.

func NewMux

func NewMux(opt *MuxOptions) *Mux

NewMux returns a new Mux that implements the http.Handler interface and can be run with http.ListenAndServe(":8000", handler). You can optionally proved an MuxOptions struct with custom settings. Any panics caused by a registered handler will be caught and optionaly logged.

func (*Mux) File

func (m *Mux) File(url, file string, mw ...Middleware)

File is a helper to serve a simple http GET response for a single file. If the file "disappears" while the server is running, a 404 Not found will be returned. NOTE: if the file doesn't exist at start up, it will cause a panic instead. You can optionally use middlewares too, the same way as in Register().

func (*Mux) Register

func (m *Mux) Register(method, url string, handler Handler, mw ...Middleware)

Register registers a new handler for a certain http method and URL. It will also handle any errors returned from the handler, by responding to the erroring request with http.Error(). You can optionally use one or more http.Handler middleware. First middleware in the list will be executed first, and then it loops forward through all middlewares and lasty executes the request handler last.

func (*Mux) RegisterPrefix

func (m *Mux) RegisterPrefix(prefix string, mw ...Middleware) RegisterFunc

RegisterPrefix returns a RegisterFunc function that you can call multiple times to register multiple handlers under a common URL prefix. You can optionally use middlewares too, the same way as in Register().

func (*Mux) ServeHTTP

func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*Mux) Static

func (m *Mux) Static(dir string, fs http.FileSystem, mw ...Middleware)

Static is a helper to serve a whole directory with static files. You can optionally use middlewares too, the same way as in Register().

type MuxOptions

type MuxOptions struct {
	// Simple logger
	Log *log.Logger
	// Templates that can be rendered using context.Render()
	Templates map[string]*template.Template
	// HandleNotFound is a Handler that will be called for '404 not found" errors. If not set it will default to
	// the SimpleNotFoundHandler() handler.
	HandleNotFound Handler
	// HandleError is a ErrorHandler that will be called for all errors returned from a Handler (except for
	// "404 not found"). It defaults to SimpleErrorHandler().
	HandleError ErrorHandler
	// Middlewares is a list of middlewares that will be globaly added to all handlers
	Middlewares []Middleware
}

MuxOptions contains all the optional settings for a Mux.

type RegisterFunc

type RegisterFunc func(string, string, Handler)

RegisterFunc is a function signature used when you want to register multiple handlers under a common URL path. First string is method, second string is the URL and last field is the Handler you want to register.

type ServerOptions

type ServerOptions struct {
	Addr    string
	Handler http.Handler
	Log     *log.Logger
}

ServerOptions contaisn settings that will be used when creating a new, secure http.Server (via NewServer()).

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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