golf

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2017 License: MIT Imports: 23 Imported by: 39

README

GoDoc License Build Status Build Status Coverage Status

A fast, simple and lightweight micro-web framework for Go, comes with powerful features and has no dependencies other than the Go Standard Library.

Homepage: golf.readme.io

Installation

go get github.com/dinever/golf

Features

  1. No allocation during routing and parameter retrieve.

  2. Dead simple template inheritance with extends and include helper comes out of box.

    layout.html

    <h1>Hello World</h1>
    {{ template "body" }}
    {{ include "sidebar.html" }}
    

    index.html

    {{ extends "layout.html" }}
    
    {{ define "body"}}
    <p>Main content</p>
    {{ end }}
    

    sidebar.html

    <p>Sidebar content</p>
    
  3. Built-in XSRF and Session support.

  4. Powerful middleware chain.

  5. Configuration from JSON file.

Hello World

package main

import "github.com/dinever/golf"

func mainHandler(ctx *golf.Context) {
  ctx.Send("Hello World!")
}

func pageHandler(ctx *golf.Context) {
  ctx.Send("Page: " + ctx.Param("page"))
}

func main() {
  app := golf.New()
  app.Get("/", mainHandler)
  app.Get("/p/:page/", pageHandler)
  app.Run(":9000")
}

The website will be available at http://localhost:9000.

Benchmark

The following chart shows the benchmark performance of Golf compared with others.

Golf benchmark

For more information, please see BENCHMARKING.md

Docs

golf.readme.io/docs

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Errorf added in v0.1.1

func Errorf(format string, parameters ...interface{}) error

Errorf returns an templateError.

Types

type Application

type Application struct {

	// The View model of the application. View handles the templating and page
	// rendering.
	View *View

	// Config provides configuration management.
	Config *Config

	SessionManager SessionManager

	// NotFoundHandler handles requests when no route is matched.
	NotFoundHandler HandlerFunc

	// The default error handler, if the corresponding error code is not specified
	// in the `errorHandler` map, this handler will be called.
	DefaultErrorHandler ErrorHandlerFunc
	// contains filtered or unexported fields
}

Application is an abstraction of a Golf application, can be used for configuration, etc.

func New

func New() *Application

New is used for creating a new Golf Application instance.

func (*Application) Delete

func (app *Application) Delete(pattern string, handler HandlerFunc)

Delete method is used for registering a Delete method route

func (*Application) Error

func (app *Application) Error(statusCode int, handler ErrorHandlerFunc)

Error method is used for registering an handler for a specified HTTP error code.

func (*Application) Get

func (app *Application) Get(pattern string, handler HandlerFunc)

Get method is used for registering a Get method route

func (*Application) Head added in v0.2.0

func (app *Application) Head(pattern string, handler HandlerFunc)

Head method is used for registering a Head method route

func (*Application) Options added in v0.2.0

func (app *Application) Options(pattern string, handler HandlerFunc)

Options method is used for registering a Options method route

func (*Application) Patch added in v0.2.0

func (app *Application) Patch(pattern string, handler HandlerFunc)

Patch method is used for registering a Patch method route

func (*Application) Post

func (app *Application) Post(pattern string, handler HandlerFunc)

Post method is used for registering a Post method route

func (*Application) Put

func (app *Application) Put(pattern string, handler HandlerFunc)

Put method is used for registering a Put method route

func (*Application) Run

func (app *Application) Run(addr string)

Run the Golf Application.

func (*Application) RunTLS

func (app *Application) RunTLS(addr, certFile, keyFile string)

RunTLS runs the app with TLS support.

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(res http.ResponseWriter, req *http.Request)

Basic entrance of an `http.ResponseWriter` and an `http.Request`.

func (*Application) Static

func (app *Application) Static(url string, path string)

Static is used for registering a static folder

func (*Application) Use added in v0.3.0

func (app *Application) Use(m ...MiddlewareHandlerFunc)

Use appends a middleware to the existing middleware chain.

type Chain

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

Chain contains a sequence of middlewares.

func NewChain

func NewChain(handlerArray ...MiddlewareHandlerFunc) *Chain

NewChain Creates a new middleware chain.

func (*Chain) Append

func (c *Chain) Append(fn MiddlewareHandlerFunc)

Append a middleware to the middleware chain

func (Chain) Final

func (c Chain) Final(fn HandlerFunc) HandlerFunc

Final indicates a final Handler, chain the multiple middlewares together with the handler, and return them together as a handler.

type Config

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

Config control for the application.

func ConfigFromJSON

func ConfigFromJSON(reader io.Reader) (*Config, error)

ConfigFromJSON creates a Config instance from a JSON io.reader.

func NewConfig

func NewConfig() *Config

NewConfig creates a new configuration instance.

func (*Config) Get

func (config *Config) Get(key string, defaultValue interface{}) (interface{}, error)

Get is used to retrieve the value by indicating a key. After calling this method you should indicate the type of the return value. If one of the parent node is not a map, then return a ValueTypeError. If the key is not found, return a KeyError.

func (*Config) GetBool

func (config *Config) GetBool(key string, defaultValue bool) (bool, error)

GetBool fetches the bool value by indicating the key. It returns a ValueTypeError if the value is not a sring.

func (*Config) GetFloat

func (config *Config) GetFloat(key string, defaultValue float64) (float64, error)

GetFloat fetches the float value by indicating the key. It returns a ValueTypeError if the value is not a sring.

func (*Config) GetInt

func (config *Config) GetInt(key string, defaultValue int) (int, error)

GetInt fetches the int value by indicating the key. It returns a ValueTypeError if the value is not a sring.

func (*Config) GetString

func (config *Config) GetString(key string, defaultValue string) (string, error)

GetString fetches the string value by indicating the key. It returns a ValueTypeError if the value is not a sring.

func (*Config) Set

func (config *Config) Set(key string, value interface{}) error

Set is used to set the value by indicating the key. If you want to set multi-level json, key can be like 'foo/bar'. For instance, `Set("foo/bar", 4)` and `Set("foo/bar2", "foo")`. If the parent key is not a map, then return a KeyError. For instance, can not set ("foo/bar", 4) after setting ("foo", 5).

type Context

type Context struct {
	// http.Request
	Request *http.Request

	// http.ResponseWriter
	Response http.ResponseWriter

	// URL Parameter
	Params Parameter

	// The application
	App *Application

	// Session instance for the current context.
	Session Session

	// Indicating if the response is already sent.
	IsSent bool
	// contains filtered or unexported fields
}

Context is a wrapper of http.Request and http.ResponseWriter.

func NewContext

func NewContext(req *http.Request, res http.ResponseWriter, app *Application) *Context

NewContext creates a Golf.Context instance.

func (*Context) Abort

func (ctx *Context) Abort(statusCode int, data ...map[string]interface{})

Abort method returns an HTTP Error by indicating the status code, the corresponding handler inside `App.errorHandler` will be called, if user has not set the corresponding error handler, the defaultErrorHandler will be called.

func (*Context) AddHeader added in v0.3.0

func (ctx *Context) AddHeader(key, value string)

AddHeader adds the key, value pair to the header. It appends to any existing values associated with key.

func (*Context) ClientIP added in v0.3.0

func (ctx *Context) ClientIP() string

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. This method is taken from https://github.com/gin-gonic/gin

func (*Context) Cookie

func (ctx *Context) Cookie(key string) (string, error)

Cookie returns the value of the cookie by indicating the key.

func (*Context) Header

func (ctx *Context) Header(key string) string

Header gets the first value associated with the given key. If there are no values associated with the key, Get returns "".

func (*Context) JSON

func (ctx *Context) JSON(obj interface{})

JSON Sends a JSON response.

func (*Context) JSONIndent added in v0.3.0

func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string)

JSONIndent Sends a JSON response, indenting the JSON as desired.

func (*Context) Loader

func (ctx *Context) Loader(name string) *Context

Loader method sets the template loader for this context. This should be done before calling `ctx.Render`.

func (*Context) Param

func (ctx *Context) Param(key string) string

Param method retrieves the parameters from url If the url is /:id/, then id can be retrieved by calling `ctx.Param(id)`

func (*Context) Query

func (ctx *Context) Query(key string, index ...int) (string, error)

Query method retrieves the form data, return empty string if not found.

func (*Context) Redirect

func (ctx *Context) Redirect(url string)

Redirect method sets the response as a 302 redirection.

func (*Context) Redirect301 added in v0.3.0

func (ctx *Context) Redirect301(url string)

Redirect301 method sets the response as a 301 redirection.

func (*Context) Render

func (ctx *Context) Render(file string, data ...map[string]interface{})

Render a template file using the built-in Go template engine.

func (*Context) RenderFromString

func (ctx *Context) RenderFromString(tplSrc string, data ...map[string]interface{})

RenderFromString renders a input string.

func (*Context) Send

func (ctx *Context) Send(body interface{})

Send the response immediately. Set `ctx.IsSent` to `true` to make sure that the response won't be sent twice.

func (*Context) SendStatus added in v0.3.0

func (ctx *Context) SendStatus(statusCode int)

SendStatus takes an integer and sets the response status to the integer given.

func (*Context) SetCookie

func (ctx *Context) SetCookie(key string, value string, expire int)

SetCookie set cookies for the request. If expire is 0, create a session cookie.

func (*Context) SetHeader added in v0.3.0

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

SetHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

func (*Context) StatusCode

func (ctx *Context) StatusCode() int

StatusCode returns the status code that golf has sent.

type Error added in v0.1.1

type Error struct {
	Message string
	Class   string
	Stack   []*Frame
	// contains filtered or unexported fields
}

Error provides more structured information about a Go error.

func NewError added in v0.1.1

func NewError(msg interface{}) Error

NewError creates a new error instance

func (Error) Error added in v0.1.1

func (e Error) Error() string

Error returns the error message

func (Error) StackTraceString added in v0.1.1

func (e Error) StackTraceString() string

StackTraceString returns the stack trace in a string format.

type ErrorHandlerFunc added in v0.2.0

type ErrorHandlerFunc func(ctx *Context, data ...map[string]interface{})

ErrorHandlerFunc is the type of the function that handles error in Golf.

type FileSystemLoader

type FileSystemLoader struct {
	BaseDir string
}

FileSystemLoader is an implementation of TemplateLoader that loads templates from file system.

func (*FileSystemLoader) LoadTemplate

func (loader *FileSystemLoader) LoadTemplate(name string) (string, error)

LoadTemplate loads a template from a file.

type Frame added in v0.1.1

type Frame struct {
	Number string `json:"number"`
	File   string `json:"file"`
	Method string `json:"method"`
}

Frame represent a stack frame inside of a Honeybadger backtrace.

type HandlerFunc added in v0.2.0

type HandlerFunc func(ctx *Context)

HandlerFunc is the type of the handler function that Golf accepts.

func RecoverMiddleware

func RecoverMiddleware(next HandlerFunc) HandlerFunc

RecoverMiddleware is the built-in middleware for recovering from errors.

func SessionMiddleware added in v0.1.1

func SessionMiddleware(next HandlerFunc) HandlerFunc

SessionMiddleware handles session of the request

func XSRFProtectionMiddleware added in v0.1.1

func XSRFProtectionMiddleware(next HandlerFunc) HandlerFunc

XSRFProtectionMiddleware is the built-in middleware for XSRF protection.

type KeyError

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

KeyError is thrown when the specified key is not found in the configuration.

func (*KeyError) Error

func (err *KeyError) Error() string

Error method implements Error method of Go standard library "error".

type MapLoader

type MapLoader map[string]string

MapLoader is a implementation of TemplateLoader that loads templates from a map data structure.

func (*MapLoader) LoadTemplate

func (loader *MapLoader) LoadTemplate(name string) (string, error)

LoadTemplate loads a template from the map.

type MemorySession

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

MemorySession is an memory based implementaion of Session.

func (*MemorySession) Delete

func (s *MemorySession) Delete(key string) error

Delete method deletes the value by given a key in the session.

func (*MemorySession) Get

func (s *MemorySession) Get(key string) (interface{}, error)

Get method gets the value by given a key in the session.

func (*MemorySession) SessionID

func (s *MemorySession) SessionID() string

SessionID returns the current ID of the session.

func (*MemorySession) Set

func (s *MemorySession) Set(key string, value interface{}) error

Set method sets the key value pair in the session.

type MemorySessionManager

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

MemorySessionManager is a implementation of Session Manager, which stores data in memory.

func NewMemorySessionManager

func NewMemorySessionManager() *MemorySessionManager

NewMemorySessionManager creates a new session manager.

func (*MemorySessionManager) Count added in v0.1.1

func (mgr *MemorySessionManager) Count() int

Count returns the number of the current session stored in the session manager.

func (*MemorySessionManager) GarbageCollection added in v0.1.1

func (mgr *MemorySessionManager) GarbageCollection()

GarbageCollection recycles expired sessions, delete them from the session manager.

func (*MemorySessionManager) NewSession

func (mgr *MemorySessionManager) NewSession() (Session, error)

NewSession creates and returns a new session.

func (*MemorySessionManager) Session

func (mgr *MemorySessionManager) Session(sid string) (Session, error)

Session gets the session instance by indicating a session id.

type MiddlewareHandlerFunc added in v0.3.0

type MiddlewareHandlerFunc func(next HandlerFunc) HandlerFunc

MiddlewareHandlerFunc defines the middleware function type that Golf uses.

func LoggingMiddleware

func LoggingMiddleware(out io.Writer) MiddlewareHandlerFunc

LoggingMiddleware is the built-in middleware for logging. This method is referred from https://github.com/gin-gonic/gin/blob/develop/logger.go#L46

type Parameter added in v0.2.0

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

Parameter holds the parameters matched in the route

func (*Parameter) ByName added in v0.2.0

func (p *Parameter) ByName(name string) (string, error)

ByName returns the url parameter by name

func (*Parameter) Len added in v0.2.0

func (p *Parameter) Len() int

Len returns number arguments matched in the provided URL

type Session

type Session interface {
	Set(key string, value interface{}) error
	Get(key string) (interface{}, error)
	Delete(key string) error
	SessionID() string
	// contains filtered or unexported methods
}

Session is an interface for session instance, a session instance contains data needed.

type SessionManager added in v0.1.1

type SessionManager interface {
	NewSession() (Session, error)
	Session(string) (Session, error)
	GarbageCollection()
	Count() int
	// contains filtered or unexported methods
}

SessionManager manages a map of sessions.

type Template

type Template struct {
	Name string
	Src  string
}

Template type stands for a template.

type TemplateLoader

type TemplateLoader interface {
	LoadTemplate(string) (string, error)
}

TemplateLoader is the loader interface for templates.

type TemplateManager

type TemplateManager struct {
	Loader  TemplateLoader
	FuncMap map[string]interface{} //template.FuncMap
}

TemplateManager handles the template loader and stores the function map.

func (*TemplateManager) Render

func (t *TemplateManager) Render(w io.Writer, name string, data interface{}) error

Render renders a template and writes it to the io.Writer interface.

func (*TemplateManager) RenderFromString

func (t *TemplateManager) RenderFromString(w io.Writer, tplSrc string, data interface{}) error

RenderFromString renders a template from string.

type ValueTypeError

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

ValueTypeError is thrown when the type of the specified value is not valid.

func (*ValueTypeError) Error

func (err *ValueTypeError) Error() string

Error method implements Error method of Go standard library "error".

type View

type View struct {
	FuncMap template.FuncMap
	// contains filtered or unexported fields
}

View handles templates rendering

func NewView

func NewView() *View

NewView creates a new View instance.

func (*View) Render

func (view *View) Render(loaderName string, filePath string, data map[string]interface{}) (string, error)

Render renders a template by indicating the file path and the name of the template loader.

func (*View) RenderFromString

func (view *View) RenderFromString(loaderName string, tplSrc string, data map[string]interface{}) (string, error)

RenderFromString does the same thing as render but renders a template by indicating the template source from tplSrc.

func (*View) SetTemplateLoader

func (view *View) SetTemplateLoader(name string, path string)

SetTemplateLoader sets the template loader by indicating the name and the path.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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