traffic

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2014 License: MIT Imports: 18 Imported by: 186 modules, 243 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Traffic

Build Status

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

Installation

go get github.com/pilu/traffic

Features

Development Features

development is the default environment. The above middlewares are loaded only in development.

If you want to run your application in production, export TRAFFIC_ENV with production as value.

TRAFFIC_ENV=production your-executable-name

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

You can use Fresh if you want to build and restart your application every time you create/modify/delete a file.

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 *traffic.Request) {
  fmt.Fprint(w, "Hello World\n")
}

func pageHandler(w traffic.ResponseWriter, r *traffic.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)

  router.Run()
}

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 *traffic.Request) {
  fmt.Fprint(w, "Hello World\n")
}

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

func pageHandler(w traffic.ResponseWriter, r *traffic.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 *traffic.Request) {
  params := r.URL.Query()
  if params.Get("api_key") != "foo" {
    w.WriteHeader(http.StatusUnauthorized)
  }
}

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

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

func addTimeHeader(w traffic.ResponseWriter, r *traffic.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)

  router.Run()
}

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       = 3000
	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)

type Middleware

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

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
	BodyWritten() bool
	Render(string, ...interface{})
	WriteJSON(data interface{})
	WriteXML(data interface{})
	WriteText(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)

type ShowErrorsMiddleware

type ShowErrorsMiddleware struct{}

func (ShowErrorsMiddleware) RenderError

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

func (ShowErrorsMiddleware) ServeHTTP

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

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)

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

Directories

Path Synopsis
examples
before-filter command
configuration command
error-handler command
middleware command
not-found command
show-errors command
simple command
splat command
static-files command
templates command

Jump to

Keyboard shortcuts

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