shgf

package module
v0.0.0-...-28acfd6 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2019 License: MIT Imports: 15 Imported by: 0

README

GoDoc Build Status Report codebeat badge

SHGF: Simple HTTP golang framework

Simple HTTP Golang Framework. Provides simple API to create an HTTP server and routes with dynamic paths, registered by HTTP method.

Main features

  • Handle URL by path and method
  • Register dynamic paths with typed params
  • Parse forms easily
  • TLS & HTTP/2
  • Static files and folders

Reference

Read all the reference documents into GoDoc article.

Documentation

All docs are in our Wiki;

Documentation

Overview

Package shgf its a simple http framework for go language. The framework provides simple API to create a HTTP server and a group of functions to register new available routes with its handler by HTTP method.

Index

Constants

This section is empty.

Variables

View Source
var HTTPStatus = map[int][]byte{
	200: []byte("OK"),
	201: []byte("Created"),
	202: []byte("Accepted"),
	203: []byte("Non-Authoritative Information"),
	204: []byte("No Content"),
	205: []byte("Reset Content"),
	206: []byte("Partial Content"),
	207: []byte("Multi-Status"),
	208: []byte("Already Reported"),
	226: []byte("IM Used"),
	300: []byte("Multiple Choices"),
	301: []byte("Moved Permanently"),
	302: []byte("Found"),
	303: []byte("See Other"),
	304: []byte("Not Modified"),
	305: []byte("Use Proxy"),
	307: []byte("Temporary Redirect"),
	308: []byte("Permanent Redirect"),
	400: []byte("Bad Request"),
	401: []byte("Unauthorized"),
	402: []byte("Payment Required"),
	403: []byte("Forbidden"),
	404: []byte("Not Found"),
	405: []byte("Method Not Allowed"),
	406: []byte("Not Acceptable"),
	407: []byte("Proxy Authentication Required"),
	408: []byte("Request Timeout"),
	409: []byte("Conflict"),
	410: []byte("Gone"),
	411: []byte("Length Required"),
	412: []byte("Precondition Failed"),
	413: []byte("Payload Too Large"),
	414: []byte("URI Too Long"),
	415: []byte("Unsupported Media Type"),
	416: []byte("Range Not Satisfiable"),
	417: []byte("Expectation Failed"),
	421: []byte("Misdirected Request"),
	422: []byte("Unprocessable Entity"),
	423: []byte("Locked"),
	424: []byte("Failed Dependency"),
	425: []byte("Too Early"),
	426: []byte("Upgrade Required"),
	428: []byte("Precondition Required"),
	429: []byte("Too Many Requests"),
	431: []byte("Request Header Fields Too Large"),
	451: []byte("Unavailable For Legal Reasons"),
	500: []byte("Internal Server Error"),
	501: []byte("Not Implemented"),
	502: []byte("Bad Gateway"),
	503: []byte("Service Unavailable"),
	504: []byte("Gateway Timeout"),
	505: []byte("HTTP Version Not Supported"),
	506: []byte("Variant Also Negotiates"),
	507: []byte("Insufficient Storage"),
	508: []byte("Loop Detected"),
	510: []byte("Not Extended"),
	511: []byte("Network Authentication Required"),
}

HTTPStatus variable contains a map of int status code and its associated []byte message.

Functions

This section is empty.

Types

type Config

type Config struct {
	Hostname          string
	Port, TLSPort     int
	Debug, HTTP2, TLS bool
	TLSCert, TLSKey   string
}

Config struct allows to developers to configure the server easily. Requires hostname and port parameters and admits TLS cert and key paths and debug and HTTP2 flags to enable it.

func BasicConf

func BasicConf(hostname string, port int) (*Config, error)

BasicConf function returns basic configration by hostname and port provided. Default configuration includes HTTP2 enabled and debug disabled.

func LocalConf

func LocalConf() *Config

LocalConf function returns basic configration for deploy server locally. Port number is an optional parameter. By default, 8080.

type Context

type Context struct {
	Request *http.Request
	Params  Params
	Form    Form
	// contains filtered or unexported fields
}

Context struct contains the current request metainformation and utils like URL route params values, pointers to following functions or functions to handle with the request body.

func (*Context) Next

func (ctx *Context) Next() *Response

Next function invokes the main handler from middleware. If the Next function is invoked outside of middleware function, internal server error is returned.

func (*Context) ParseForm

func (ctx *Context) ParseForm() (err error)

ParseForm function invokes form function to parse the current request body to Form struct and append it into the current context. If an error occurs, it is returned.

func (*Context) ParseParams

func (ctx *Context) ParseParams() (err error)

ParseParams function extract values of URL params defined by current route. Every param are labeled, so ParseParams only extract the values that match with route matcher naming each one with its label, and casting it with the type associated. All the params are stored into Params parameter of Context.

type Form

type Form map[string]interface{}

Form type envolves a map of string and interface{}, and represents a set of path params. Provides its own functions to help to the developer to check if param exists or get a param by key safely.

func (Form) Exists

func (f Form) Exists(key string) bool

Exists function returns if provided key is currently in the parsed form.

func (Form) Get

func (f Form) Get(key string) (interface{}, error)

Get function returns a single form key, if it exists, by the key provided.

type Handler

type Handler func(*Context) *Response

Handler type wraps handler function that receives a Context pointer and returns a Response pointer as a result of handled Request.

type Params

type Params map[string]interface{}

Params type envolves a map of string and interface{}, and represents a set of path params. Provides its own functions to help to the developer to check if param exists or get a param by key safely.

func (Params) Exists

func (p Params) Exists(key string) bool

Exists function returns if provided key is currently in the parsed params.

func (Params) Get

func (p Params) Get(key string) (interface{}, error)

Get function returns a single param key, if it exists, by the key provided.

type Response

type Response struct {
	Status int
	Header map[string][]string
	Body   []byte
}

Response struct its a simplified abstraction of a HTTP response with Header, Status and Body.

func BadRequest

func BadRequest(err ...interface{}) (r *Response)

BadRequest function creates a error Response with "Bad Request" HTTP status code and sets as Body the default status message with a parsed a set of err interface{} as ServerErr.

func Forbidden

func Forbidden(err ...interface{}) (r *Response)

Forbidden function creates a error Response with "Forbidden" HTTP status code and sets as Body the default status message with a parsed a set of err interface{} as ServerErr.

func InternalServerErr

func InternalServerErr(err ...interface{}) (r *Response)

InternalServerErr function creates a error Response with "Internal Server Error" HTTP status code and sets as Body the default status message with a parsed a set of err interface{} as ServerErr.

func MethodNotAllowed

func MethodNotAllowed(err ...interface{}) (r *Response)

MethodNotAllowed function creates a error Response with "Method Not Allowed" HTTP status code and sets as Body the default status message with a parsed a set of err interface{} as ServerErr.

func NewResponse

func NewResponse(s int, d ...interface{}) (r *Response, e error)

NewResponse function creates a Response by status int code and a (optional) candidate to body. The function creates a default internal server response, checks if some data is provided as body and parses it, checks if the provided status is valid and returns a Response.

func NotFound

func NotFound(err ...interface{}) (r *Response)

NotFound function creates a error Response with "Not Found" HTTP status code and sets as Body the default status message with a parsed a set of err interface{} as ServerErr.

func StaticFile

func StaticFile(path string) *Response

StaticFile function splits the path provided into root and filename. With the resulting root creates a StaticFolder on-the-fly and returns the response composed by the StaticFolder with the resulting filename. If something was wrong, catch the resulting error and returns a response according to it.

func (*Response) JSON

func (r *Response) JSON(d interface{}) (e error)

JSON function parses provided data interface{} to []byte marshaling it and sets HTTP header JSON Content-type and parsed data as Body of current Response.

type Server

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

Server struct contains the server's hostname and port. Server, also has a base server associated. Any Server instance has associated functions to register new routes with its handler by HTTP method.

func New

func New(conf *Config) (srv *Server, err error)

New function creates a new Server instance with config by the user. If debug mode is enabled, all inbound and outbound request will be logged.

func (*Server) Connect

func (srv *Server) Connect(path string, handlers ...Handler) error

Connect function add new route on CONNECT HTTP method with path and handlers provided.

func (*Server) Delete

func (srv *Server) Delete(path string, handlers ...Handler) error

Delete function add new route on DELETE HTTP method with path and handlers provided.

func (*Server) Get

func (srv *Server) Get(path string, handlers ...Handler) error

Get function add new route on GET HTTP method with path and handlers provided.

func (*Server) Head

func (srv *Server) Head(path string, handlers ...Handler) error

Head function add new route on HEAD HTTP method with path and handlers provided.

func (*Server) Listen

func (srv *Server) Listen() error

Listen function starts base server to listen new requests.

func (*Server) Options

func (srv *Server) Options(path string, handlers ...Handler) error

Options function add new route on OPTIONS HTTP method with path and handlers provided.

func (*Server) Patch

func (srv *Server) Patch(path string, handlers ...Handler) error

Patch function add new route on PATCH HTTP method with path and handlers provided.

func (*Server) Post

func (srv *Server) Post(path string, handlers ...Handler) error

Post function add new route on POST HTTP method with path and handlers provided.

func (*Server) Put

func (srv *Server) Put(path string, handlers ...Handler) error

Put function add new route on PUT HTTP method with path and handlers provided.

func (*Server) Trace

func (srv *Server) Trace(path string, handlers ...Handler) error

Trace function add new route on TRACE HTTP method with path and handlers provided.

type ServerErr

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

ServerErr struct is a custom error for shgf that contains and simple message and original error.

func NewServerErr

func NewServerErr(msg string, err ...interface{}) (e ServerErr)

NewServerErr function creates new ServerErr by message and (optional) error provided as arguments. The function assing the message provided to custom ServerErr, checks if error exists and casts it to error.

func (ServerErr) Details

func (e ServerErr) Details() string

Details function returns merged string between ServerErr message and error.

func (ServerErr) Error

func (e ServerErr) Error() string

Error function implements Error() function from Error interface.

type StaticFolder

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

StaticFolder struct contains the root path for listen requests and has own functions to serve static files for this root path.

func NewStaticFolder

func NewStaticFolder(path string) (r *StaticFolder, err error)

NewStaticFolder function initializes the folder by the root path provided. If the path is not absolute, the function gets the current path and join with it.

func (*StaticFolder) Serve

func (r *StaticFolder) Serve(file string) *Response

Serve function composes a response with the file read, from the filename provided. The function calls composePath to get the file path, then gets the MIME Type of the file and sets it as response header. Then reads the file and writes its content into the response body.

Jump to

Keyboard shortcuts

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