This section is empty.


This section is empty.


func NewPortInUseError

func NewPortInUseError(msg error) error

NewPortInUseError create a new instance of PortInUseError with a simple error string.

func NewPortInUseErrorF

func NewPortInUseErrorF(f string, args ...interface{}) error

NewPortInUseErrorF creates a new instance of the error PortInUseError with arguments similar to printf.


type BaseHeader

type BaseHeader map[string][]string

BaseHeader is the type used for storing header information for response.

func (BaseHeader) AddAll

func (header BaseHeader) AddAll(newHeaders map[string][]string)

AddAll takes key-value pairs of the passed map and makes them headers.

func (BaseHeader) AddHeader

func (header BaseHeader) AddHeader(key string, value string)

AddHeader adds a specific header.

func (BaseHeader) AddMultipleHeaders

func (header BaseHeader) AddMultipleHeaders(key string, value []string)

AddMultipleHeaders adds multiple headers.

func (BaseHeader) DeleteHeader

func (header BaseHeader) DeleteHeader(key string, value string)

DeleteHeader deletes a specific header.

func (BaseHeader) GetHeader

func (header BaseHeader) GetHeader(key string) []string

GetHeader returns a specific header.

func (BaseHeader) Map

func (header BaseHeader) Map() map[string][]string

type BaseResponse

type BaseResponse struct {
	// contains filtered or unexported fields

BaseResponse is the basic data structure used for constructing an HTTP response.

func New404Response

func New404Response() *BaseResponse

New404Response creates a HTTP 404 response

func NewBaseResponse

func NewBaseResponse() *BaseResponse

NewBaseResponse creates a new response that has all the necessary functionality for an HTTP response.

func (*BaseResponse) GetStatusCode

func (baseResponse *BaseResponse) GetStatusCode() int

GetStatusCode return the status code of the response.

func (*BaseResponse) Headers

func (baseResponse *BaseResponse) Headers() Headers

Headers returns the headers of the response.

func (*BaseResponse) SetStatusCode

func (baseResponse *BaseResponse) SetStatusCode(statusCode int)

SetStatusCode sets the status code of the response.

type File

type File struct {
	// contains filtered or unexported fields

File represents a file that is sent via HTTP

func (*File) Close

func (file *File) Close() (err error)

Close closes the file, preventing any further operations on the file.

func (*File) Filename

func (file *File) Filename() string

Filename returns the filename of the file as sent via the request payload.

func (*File) Read

func (file *File) Read(p []byte) (n int, err error)

Read read the file into the passed buffer, returning the number of bytes actually read.

func (*File) Size

func (file *File) Size() int64

Size returns the size of the file uploaded as reported by the request headers. Do not necessarily rely on this number being accurate because it comes from the client.

type HandlerFunc

type HandlerFunc func(request *Request) (response Response, err error)

HandlerFunc is the defines a type of function that handles a request.

type Headers

type Headers interface {

	// GetHeader returns a specific header
	GetHeader(key string) []string

	// AddHeader sets a new header. Duplicate allowed as per the HTTP spec.
	AddHeader(key string, value string)

	// AddMultipleHeaders add the same header with multiple values.
	AddMultipleHeaders(key string, value []string)

	// DeleteHeader removes a header.
	DeleteHeader(key string, value string)

	// AddAll takes key-value pairs of the passed map and makes them headers.
	AddAll(headers map[string][]string)

	// Map returns a map containing all the headers.
	Map() map[string][]string

Headers is an interface used for interacting with an HTTP header.

type JSONResponse

type JSONResponse struct {
	// contains filtered or unexported fields

JSONResponse represents a response containing JSON.

func NewJSONResponse

func NewJSONResponse(subject interface{}) *JSONResponse

NewJSONResponse creates a response with a passed struct that will be marshalled into JSON when the response is sent.

func (*JSONResponse) MarshalJSON

func (jsonResponse *JSONResponse) MarshalJSON() (subjectJSON []byte, err error)

MarshalJSON marshals the JSONResponse into json.

type Logger

type Logger struct {
	// contains filtered or unexported fields

Logger presents a log file that can

func NewLogger

func NewLogger(logFilePath string) Logger

NewLogger creates a new logger than can be used for performing non-blocking logging.

type Method

type Method int

Method is the HTTP method to use for a route.

const (
	// Get is the GET Http method.
	Get Method = 1

	// Post is the POST Http method.
	Post Method = 2

	// Put is the PUT HTTP method.
	Put Method = 3

	// Delete is the DELETE HTTP method.
	Delete Method = 4

	// Head is the HEAD HTTP method.
	Head Method = 5

func (Method) String

func (i Method) String() string

type Options

type Options struct {

	// The host and port for the server to listen on.
	Address string

	// ReadTimeout is the maximum duration for reading the entire request, including the body.
	ReadTimeOut int

	// WriteTimeout is the maximum duration before timing out writes of the response.
	WriteTimeout int

	// MaxHeaderBytes controls the maximum number of bytes the server will read parsing the request header's keys and
	// values, including the request line.
	MaxHeaderBytes int

	// StateChangeHandler is handler that is called when the general state of the server changes, such as
	// when starting or shutting down. The change state handler must return an error when it receives an interrupt
	// state.
	StateChangeHandler *StateChangeHandlerType

	// JSONDecoder is the json decoder used for decoding JSON requests.
	JSONDecoder func(r io.Reader) *json.Decoder

	// JSONDecoder is the json encoder used for encoding responses into JSON.
	JSONEncoder func(r io.Writer) *json.Encoder

	// LogFilePath is the file path to write the log file.
	LogFilePath string

	// LogFileRollSize the max size in bytes of the log file needs to be before rolling into a new logfile.
	LogFileRollSize int64

Options is the set of configuration options for the server.

type PortInUseError

type PortInUseError struct {
	// contains filtered or unexported fields

PortInUseError is a generated error type.

func (*PortInUseError) CausedBy

func (err *PortInUseError) CausedBy() error

CausedBy returns the error that cause the error. The error returned may also have a cause.

func (*PortInUseError) Error

func (err *PortInUseError) Error() string

Error returns a string representation of the error.

func (*PortInUseError) Stack

func (err *PortInUseError) Stack() *errors.StackTrace

Stack returns the call stack of the error.

type Request

type Request struct {
	// contains filtered or unexported fields

Request is the HTTP Request that was made to the server.

func (*Request) LoadJSON

func (request *Request) LoadJSON(structValue interface{}) error

LoadJSON unmarshals the request into a struct.

func (*Request) LookupHeader

func (request *Request) LookupHeader(key string) (header []string, ok bool)

LookupHeader returns a header that matches the provided key. Ok can be used to determine the presence of the header.

func (*Request) LookupParameter

func (request *Request) LookupParameter(key string) (param []string, ok bool)

LookupParameter returns any matching parameters and a boolean that is set to true if any matching values were found. Parameter refer to key value pairs in the querystring.

func (*Request) LookupSingleParameter

func (request *Request) LookupSingleParameter(key string) (param string, ok bool)

LookupSingleParameter returns the first matching parameter found. Ok can be used to determine whether any matches were found.

func (*Request) LookupURIParameter

func (request *Request) LookupURIParameter(key string) (param interface{}, ok bool)

LookupURIParameter returns the parameter found the uri as specified in the route. If the route is /my/uri/id/<id:string> then LookupURIParameter can be used to retrieve the id.

func (*Request) WithFile

func (request *Request) WithFile(key string, f func(file *File) (interface{}, error)) (ret interface{}, err error)

WithFile looks for the file the provided key in the request, and called a function with the file that can be read. Any value or error return from the function is also returned by WidthFile.

type Response

type Response interface {

	// GetStatusCode returns the status code of the HTTP response.
	GetStatusCode() int

	// Headers return the header for the HTTP response.
	Headers() Headers

Response is the interface use to represent an HTTP response.

type Server

type Server struct {
	// State represents the current state of the Server. It is better to use a state change handler to
	// respond to state changes.
	State   State
	Options *Options
	// contains filtered or unexported fields

Server is an HTTP server that can be configured with various routes.


ExampleServer shows how to setup a complete server.

var httpServer *Server

var handler StateChangeHandlerType

// Setup a state change handler that is called when the server is starting up, shutting down ...etc.
handler = func(i State, args []interface{}) error {
	log.Printf("state: %d", i)
	log.Printf("args: %v", args)
	return nil

httpServer = New(&Options{
	LogFilePath:        "./log.log",
	StateChangeHandler: &handler,
	Address:            "localhost:1984",

// For the sake of simplicity in this example, every response sends this dummy user record.
baseResponse := NewJSONResponse(struct {
	UserName string `json:"userName"`
}{"john smith"})

httpServer.Route(Get, "/user", func(request *Request) (response Response, err error) {
	return baseResponse, nil

httpServer.Route(Get, "/user/<id:string>", func(request *Request) (response Response, err error) {
	return baseResponse, nil

httpServer.Route(Get, "/user/<id:string>/name/<firstname:string>", func(request *Request) (response Response, err error) {
	return baseResponse, nil

httpServer.Route(Get, "/user/<id:string>/name/<firstname:int>/<lastname:int>", func(request *Request) (response Response, err error) {
	return baseResponse, nil

httpServer.Route(Get, "/search/<name:string>", func(request *Request) (response Response, err error) {

	return baseResponse, nil

httpServer.Route(Get, "/search/<name:string>/page/<pageNum:int>", func(request *Request) (response Response, err error) {

	return baseResponse, nil

// Start the server and begin serving.

// Print out the routes for making it obvious what the server is doing.

fmt.Print("Now serving...")
// Blocks until the server receives an interrupt, shutting down the server and calling the state change handler.

func New

func New(options *Options) *Server

New creates a new server

func (*Server) GetParameterizedRoutePaths

func (server *Server) GetParameterizedRoutePaths() (allRoutes map[Method][]string)

GetParameterizedRoutePaths returns a map of Method to a full route path.

func (*Server) GetStaticRoutePaths

func (server *Server) GetStaticRoutePaths() (routePaths map[Method][]string)

GetStaticRoutePaths returns a map of Method to a full route path.

func (*Server) Log

func (server *Server) Log(message string)

Log writes a message to the server log. The write operation is non-blocking.

func (*Server) Route

func (server *Server) Route(method Method, uri URI, f HandlerFunc)

Route defines a new route that the server handles. Method is either Get, Post, Delete, Head, Put. URI is a string describing a uri to handle. The URI can either be a static route, such as /users/list or a parameterized path, /users/<id:string> The associated handler function is called when a request is received that matches the uri.

func (*Server) RoutePaths

func (server *Server) RoutePaths() string

RoutePaths return a ASCII table of the routes.

func (*Server) ServeHTTP

func (server *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHttp is public because it is required by the http.Handler interface. Not meant to used by clients.

func (*Server) Start

func (server *Server) Start() error

Start begins the http server. Must call WaitForInterrupt sometime after to ensure server remains running.

func (*Server) StartLogging

func (server *Server) StartLogging()

StartLogging starts a Go-routine that writes to the log periodically.

func (*Server) Stop

func (server *Server) Stop()

func (*Server) WaitForInterrupt

func (server *Server) WaitForInterrupt()

WaitForInterrupt only returns when the process has received an interrupt signal to shutdown. Periodically we check for errors and if any are found we panic. The error handler is suppose to resolve any errors but if there are errors that it propagated, we assume the error is big enough that we need to stop everything.

type State

type State int8

State represents the state of the server.

const (
	// Init is the initial state of the server.
	Init State = iota

	//BeforeRun is the state of the server before it is ran.

	// Running is the state of the server indicating that the server is running

	//BeforeStop is the state of the server it is about to stop.

	// Stopped is the state indicating that the server has been stopped.

	// Interrupt is the state indicating that the server has received an interrupt and is transitioning to stopped.

	// Error is the state indicating that the server has had an error that is unrecoverable.

func (State) String

func (state State) String() string

type StateChangeHandlerType

type StateChangeHandlerType func(state State, args []interface{}) error

StateChangeHandlerType is a handler that is called when the server changes state.

type StringResponse

type StringResponse struct {
	// contains filtered or unexported fields

StringResponse is an Http response that contains a string only.

func NewStringResponse

func NewStringResponse(string string) *StringResponse

func (*StringResponse) String

func (stringResponse *StringResponse) String() string

String returns the string value of the response.

type URI

type URI string

URI is a http URI