traffic

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2013 License: MIT Imports: 18 Imported by: 0

README

Traffic

Build Status

Package traffic - a Sinatra inspired regexp/pattern mux for Go.

Installation

go get github.com/pilu/traffic

Features

Development Features

Installation

Dowload the Traffic code:

go get github.com/pilu/traffic

Build the command line tool:

go get github.com/pilu/traffic/traffic

Create a new project:

traffic new hello

Run your project:

cd hello
go build && ./hello

A command line runner is in development. It will build and run the project every time a file is created/modified.

Example:

The following code is a simple example, the documentation in still in development. For more examples check the examples folder.

package main

import (
  "net/http"
  "github.com/pilu/traffic"
  "fmt"
)

func rootHandler(w traffic.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "Hello World\n")
}

func pageHandler(w traffic.ResponseWriter, r *http.Request) {
  params := r.URL.Query()
  fmt.Fprintf(w, "Category ID: %s\n", params.Get("category_id"))
  fmt.Fprintf(w, "Page ID: %s\n", params.Get("id"))
}

func main() {
  router := traffic.New()

  // Routes
  router.Get("/", rootHandler)
  router.Get("/categories/:category_id/pages/:id", pageHandler)

  http.Handle("/", router)
  http.ListenAndServe(":7000", nil)
}

Before Filters

You can also add "before filters" to all your routes or just to some of them:

router := traffic.New()

// Executed before all handlers
router.AddBeforeFilter(checkApiKey).
       AddBeforeFilter(addAppNameHeader).
       AddBeforeFilter(addTimeHeader)

// Routes
router.Get("/", rootHandler)
router.Get("/categories/:category_id/pages/:id", pageHandler)

// "/private" has one more before filter that checks for a second api key (private_api_key)
router.Get("/private", privatePageHandler).
        AddBeforeFilter(checkPrivatePageApiKey)

Complete example:

func rootHandler(w traffic.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "Hello World\n")
}

func privatePageHandler(w traffic.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "Hello Private Page\n")
}

func pageHandler(w traffic.ResponseWriter, r *http.Request) {
  params := r.URL.Query()
  fmt.Fprintf(w, "Category ID: %s\n", params.Get("category_id"))
  fmt.Fprintf(w, "Page ID: %s\n", params.Get("id"))
}

func checkApiKey(w traffic.ResponseWriter, r *http.Request) {
  params := r.URL.Query()
  if params.Get("api_key") != "foo" {
    w.WriteHeader(http.StatusUnauthorized)
  }
}

func checkPrivatePageApiKey(w traffic.ResponseWriter, r *http.Request) {
  params := r.URL.Query()
  if params.Get("private_api_key") != "bar" {
    w.WriteHeader(http.StatusUnauthorized)
  }
}

func addAppNameHeader(w traffic.ResponseWriter, r *http.Request) {
  w.Header().Add("X-APP-NAME", "My App")
}

func addTimeHeader(w traffic.ResponseWriter, r *http.Request) {
  t := fmt.Sprintf("%s", time.Now())
  w.Header().Add("X-APP-TIME", t)
}

func main() {
  router := traffic.New()

  // Routes
  router.Get("/", rootHandler)
  router.Get("/categories/:category_id/pages/:id", pageHandler)
  // "/private" has one more before filter that checks for a second api key (private_api_key)
  router.Get("/private", privatePageHandler).
          AddBeforeFilter(checkPrivatePageApiKey)

  // Executed before all handlers
  router.AddBeforeFilter(checkApiKey).
         AddBeforeFilter(addAppNameHeader).
         AddBeforeFilter(addTimeHeader)

  http.Handle("/", router)
  http.ListenAndServe(":7000", nil)
}

Author

More

Documentation

Overview

Package traffic - a Sinatra inspired regexp/pattern mux for Go.

Docs and examples are on github: https://github.com/pilu/traffic/

Index

Constants

View Source
const (
	EnvDevelopment    = "development"
	DefaultViewsPath  = "views"
	DefaultPublicPath = "public"
	DefaultConfigFile = "traffic.conf"
	DefaultPort       = 7000
	DefaultHost       = "127.0.0.1"
)
View Source
const TemplateExtension = ".tpl"

Variables

This section is empty.

Functions

func ConfigFilePath

func ConfigFilePath() string

func Env

func Env() string

func GetVar

func GetVar(key string) interface{}

func Host

func Host() string

func Port

func Port() int

func PublicPath

func PublicPath() string

func RenderTemplate added in v0.3.0

func RenderTemplate(w ResponseWriter, templateName string, data ...interface{})

func RootPath

func RootPath() string

func SetHost

func SetHost(host string)

func SetLogger

func SetLogger(customLogger ILogger)

func SetPort

func SetPort(port int)

func SetVar

func SetVar(key string, value interface{})

func TemplateFunc added in v0.4.0

func TemplateFunc(name string, fn interface{})

func TemplateFuncs added in v0.4.0

func TemplateFuncs(funcs map[string]interface{})

func ViewsPath

func ViewsPath() string

Types

type ErrorHandlerFunc

type ErrorHandlerFunc func(ResponseWriter, *Request, interface{})

type HttpHandleFunc

type HttpHandleFunc func(ResponseWriter, *Request)

type HttpMethod

type HttpMethod string

type ILogger

type ILogger interface {
	Print(...interface{})
	Printf(string, ...interface{})
}

func Logger

func Logger() ILogger

type LoggerMiddleware

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

func (*LoggerMiddleware) ServeHTTP

func (loggerMiddleware *LoggerMiddleware) ServeHTTP(w ResponseWriter, r *Request, next NextMiddlewareFunc) (ResponseWriter, *Request)

type Middleware

type Middleware interface {
	ServeHTTP(ResponseWriter, *Request, NextMiddlewareFunc) (ResponseWriter, *Request)
}

type NextMiddlewareFunc

type NextMiddlewareFunc func() Middleware

type RenderFunc

type RenderFunc func(w ResponseWriter, template string, data interface{})

type Request added in v0.3.0

type Request struct {
	*http.Request
}

func (Request) Param added in v0.3.0

func (r Request) Param(key string) string

func (Request) Params added in v0.3.0

func (r Request) Params() url.Values

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	SetVar(string, interface{})
	GetVar(string) interface{}
	StatusCode() int
	Written() bool
	RenderTemplate(string, ...interface{})
	RenderJSON(data interface{})
	RenderXML(data interface{})
	RenderText(string, ...interface{})
}

type Route

type Route struct {
	Path       string
	PathRegexp *regexp.Regexp
	Handlers   []HttpHandleFunc
	// contains filtered or unexported fields
}

func NewRoute

func NewRoute(path string, handlers ...HttpHandleFunc) *Route

func (*Route) AddBeforeFilter

func (route *Route) AddBeforeFilter(beforeFilters ...HttpHandleFunc) *Route

func (Route) Match

func (route Route) Match(path string) (url.Values, bool)

type Router

type Router struct {
	NotFoundHandler HttpHandleFunc
	ErrorHandler    ErrorHandlerFunc
	// contains filtered or unexported fields
}

func New

func New() *Router

func (*Router) Add

func (router *Router) Add(method HttpMethod, path string, handlers ...HttpHandleFunc) *Route

func (*Router) AddBeforeFilter

func (router *Router) AddBeforeFilter(beforeFilters ...HttpHandleFunc) *Router

func (*Router) Delete

func (router *Router) Delete(path string, handlers ...HttpHandleFunc) *Route

func (*Router) Get

func (router *Router) Get(path string, handlers ...HttpHandleFunc) *Route

func (*Router) GetVar

func (router *Router) GetVar(key string) interface{}

func (Router) MiddlewareEnumerator

func (router Router) MiddlewareEnumerator() func() Middleware

func (*Router) Patch

func (router *Router) Patch(path string, handlers ...HttpHandleFunc) *Route

func (*Router) Post

func (router *Router) Post(path string, handlers ...HttpHandleFunc) *Route

func (*Router) Put

func (router *Router) Put(path string, handlers ...HttpHandleFunc) *Route

func (*Router) Run

func (router *Router) Run()

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(httpResponseWriter http.ResponseWriter, httpRequest *http.Request)

func (*Router) SetVar

func (router *Router) SetVar(key string, value interface{})

func (*Router) Use added in v0.4.0

func (router *Router) Use(middleware Middleware)

type RouterMiddleware

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

func (*RouterMiddleware) ServeHTTP

func (routerMiddleware *RouterMiddleware) ServeHTTP(w ResponseWriter, r *Request, next NextMiddlewareFunc) (ResponseWriter, *Request)

type ShowErrorsMiddleware

type ShowErrorsMiddleware struct{}

func (ShowErrorsMiddleware) RenderError

func (middleware ShowErrorsMiddleware) RenderError(w ResponseWriter, r *Request, err interface{}, stack []byte)

func (ShowErrorsMiddleware) ServeHTTP

type StaticMiddleware

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

func NewStaticMiddleware

func NewStaticMiddleware(publicPath string) *StaticMiddleware

func (*StaticMiddleware) ServeHTTP

func (middleware *StaticMiddleware) ServeHTTP(w ResponseWriter, r *Request, next NextMiddlewareFunc) (ResponseWriter, *Request)

type TemplateManager

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

func (*TemplateManager) Render

func (t *TemplateManager) Render(w ResponseWriter, template string, data interface{})

func (*TemplateManager) RenderTemplateErrors

func (t *TemplateManager) RenderTemplateErrors(w ResponseWriter, template string, data interface{})

func (*TemplateManager) WalkFunc

func (t *TemplateManager) WalkFunc(path string, info os.FileInfo, err error) error

Jump to

Keyboard shortcuts

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