tiny

package module
v0.0.0-...-24d406a Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2017 License: MIT Imports: 17 Imported by: 2

README

Go tiny http router or web framework

Reinventing the wheel, reinventing the best wheel.

Features
  • lightweight and high performance
  • work with tiny/http handlers
  • support multiple/yield handlers
  • take care for 501/trailing slash/cleaned path/405/404
  • support any method/group subrouter
  • named type/catch-all/regexp parameters
  • context values/remote ip/first query/convenient methods/environment
  • access log/compress
Usage
package main

import (
  "fmt"
  "net/http"

  "github.com/cxr29/log"
  "github.com/cxr29/tiny"
)

func main() {
  r := new(tiny.Router)

  // one or more handlers(handler is equivalent to middleware)
  r.Use(TinyHandler{}, HTTPHandler{})
  r.Use(TinyHandlerFunc, HTTPHandlerFunc)

  // call to yield after the rest handlers have been executed
  r.Use(func(ctx *tiny.Context) {
    fmt.Println("before")
    ctx.Next()
    fmt.Println("after")
  })

  // builtin handlers for no routes match
  //  501 Not Implemented
  //  try trailing slash, permanent redirect
  //  try cleaned path, permanent redirect
  //  405 Method Not Allowed
  //  404 Not Found
  r.Fallback()
  // or DIY
  r.Use(
    tiny.HandleNotImplemented,
    tiny.NewRedirectTrailingSlash(false), // try trailing slash, temporary redirect
    tiny.NewRedirectCleanedPath(false),   // try cleaned path, temporary redirect
    tiny.NewAllowedMethods(false),        // no auto-handle, just set the Allow header
    func(ctx *tiny.Context) {
      // already routed
      if ctx.Routed() {
        return
      }

      allowedMethods := ctx.Header().Get("Allow")
      if allowedMethods == "" { // no allowed methods
        ctx.NotFound()
        return
      }

      // comma-separated allowed methods
      fmt.Println(allowedMethods)

      if ctx.Request.Method == "OPTIONS" { // 200
        ctx.WriteHeader(http.StatusOK)
      } else { // 405
        ctx.WriteHeader(http.StatusMethodNotAllowed)
        ctx.WriteString(http.StatusText(http.StatusMethodNotAllowed))
      }
    },
  )

  // method handlers
  r.GET("/", handlers...)
  r.POST("/foo", handlers...)
  // ...

  // any method handlers
  r.Any("/foo", handlers...) // only when no explicit method routes match

  // group handlers
  r.Group("/foo/bar", func(r *tiny.Router) {
    // subrouter just the same
  }, handlers...) // handlers called before the subrouter's handlers

  // named parameters match anything except slashes
  //  /foo      match
  //  /foo/     no match
  //  /foo/bar  no match
  r.GET("/<name>", func(ctx *tiny.Context) {
    // get param by name
    fmt.Println(ctx.Param("name"))
    // or by index
    fmt.Println(ctx.Params[0])
  })

  // named type parameters
  // boolean match true/false
  r.GET("/<long:boolean>/<short:bool>/<even:b>")

  // integer match well-formed integers
  r.GET("/<long:integer>/<short:int>/<even:i>")

  // number match well-formed numbers
  r.GET("/<long:number>/<short:num>/<even:n>")

  // string/catch-all match anything include slashes
  r.GET("/<long:string>/<short:str>/<even:s>")

  // caret represents begin match the regexp
  r.GET(`/<name^[0-9]+>`)

  log.ErrFatal(tiny.ListenAndServe(":8080", r.Handler()))
}
I hate writing documentation but RTFSC.
I hate writing test cases but I have tested it. I did my best.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultRouter = new(Router)

Functions

func Dev

func Dev() bool

func Env

func Env() string

func Group

func Group(pattern string, f func(*Router), handlers ...interface{})

func HandleNotFound

func HandleNotFound(ctx *Context)

func HandleNotImplemented

func HandleNotImplemented(ctx *Context)

func ListenAndServe

func ListenAndServe(addr string, handler http.Handler) error

func ListenAndServeFCGI

func ListenAndServeFCGI(addr string, handler http.Handler) error

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error

func NewValueKey

func NewValueKey() (key valueKey)

func Prod

func Prod() bool

func SetEnv

func SetEnv(s string)

func Test

func Test() bool

func Use

func Use(handlers ...interface{})

Types

type Context

type Context struct {
	http.ResponseWriter
	Request *http.Request
	Values  map[interface{}]interface{}
	Params  []string
	// contains filtered or unexported fields
}

func (*Context) BadRequest

func (ctx *Context) BadRequest()

func (*Context) ContentDisposition

func (ctx *Context) ContentDisposition(filename, fallback string)

func (*Context) ContentLength

func (ctx *Context) ContentLength(i int)

func (*Context) ContentType

func (ctx *Context) ContentType(s string)

func (*Context) ContentTypeCSV

func (ctx *Context) ContentTypeCSV()

func (*Context) ContentTypeHTML

func (ctx *Context) ContentTypeHTML()

func (*Context) ContentTypeJSON

func (ctx *Context) ContentTypeJSON()

func (*Context) ContentTypePlain

func (ctx *Context) ContentTypePlain()

func (*Context) ContentTypeXLSX

func (ctx *Context) ContentTypeXLSX()

func (*Context) ContentTypeXML

func (ctx *Context) ContentTypeXML()

func (*Context) DecodeJSON

func (ctx *Context) DecodeJSON(v interface{}) error

func (*Context) DecodeXML

func (ctx *Context) DecodeXML(v interface{}) error

func (*Context) ETag

func (ctx *Context) ETag(s string)

func (*Context) First

func (ctx *Context) First(k string) (s string, n int)

func (*Context) FirstBool

func (ctx *Context) FirstBool(k string) (bool, int)

func (*Context) FirstFloat32

func (ctx *Context) FirstFloat32(k string) (float32, int)

func (*Context) FirstFloat64

func (ctx *Context) FirstFloat64(k string) (float64, int)

func (*Context) FirstInt

func (ctx *Context) FirstInt(k string) (int, int)

func (*Context) FirstUint

func (ctx *Context) FirstUint(k string) (uint, int)

func (*Context) Forbidden

func (ctx *Context) Forbidden()

func (*Context) Found

func (ctx *Context) Found(location string)

func (*Context) IfModifiedSince

func (ctx *Context) IfModifiedSince(t time.Time) bool

func (*Context) IfNoneMatch

func (ctx *Context) IfNoneMatch(s string) bool

func (*Context) InternalServerError

func (ctx *Context) InternalServerError()

func (*Context) IsAJAX

func (ctx *Context) IsAJAX() bool

func (*Context) LastModified

func (ctx *Context) LastModified(t time.Time)

func (*Context) MaxAge

func (ctx *Context) MaxAge(seconds int)

func (*Context) MovedPermanently

func (ctx *Context) MovedPermanently(location string)

func (*Context) Next

func (ctx *Context) Next()

func (*Context) NoCache

func (ctx *Context) NoCache()

func (*Context) NotFound

func (ctx *Context) NotFound()

func (*Context) NotModified

func (ctx *Context) NotModified()

func (*Context) Param

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

func (*Context) ParamBool

func (ctx *Context) ParamBool(name string) (bool, bool)

func (*Context) ParamFloat32

func (ctx *Context) ParamFloat32(name string) (float32, bool)

func (*Context) ParamFloat64

func (ctx *Context) ParamFloat64(name string) (float64, bool)

func (*Context) ParamInt

func (ctx *Context) ParamInt(name string) (int, bool)

func (*Context) ParamUint

func (ctx *Context) ParamUint(name string) (uint, bool)

func (*Context) ParseRemoteIP

func (ctx *Context) ParseRemoteIP(realIP, forwardedFor bool) net.IP

func (*Context) RemoteIP

func (ctx *Context) RemoteIP() (ip net.IP)

func (*Context) Routed

func (ctx *Context) Routed() bool

func (*Context) ServeFile

func (ctx *Context) ServeFile(name string)

func (*Context) ServiceUnavailable

func (ctx *Context) ServiceUnavailable()

func (*Context) SetRemoteIP

func (ctx *Context) SetRemoteIP(ip net.IP)

func (*Context) SetValue

func (ctx *Context) SetValue(k, v interface{})

func (*Context) Status

func (ctx *Context) Status() int

func (*Context) Value

func (ctx *Context) Value(k interface{}) interface{}

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

func (*Context) WriteData

func (ctx *Context) WriteData(v interface{}) (int, error)

func (*Context) WriteError

func (ctx *Context) WriteError(e interface{}) (int, error)

func (*Context) WriteErrorf

func (ctx *Context) WriteErrorf(format string, a ...interface{}) (int, error)

func (*Context) WriteHeader

func (ctx *Context) WriteHeader(code int)

func (*Context) WriteJSON

func (ctx *Context) WriteJSON(v interface{}) (int, error)

func (*Context) WritePlain

func (ctx *Context) WritePlain(s string) (int, error)

func (*Context) WriteString

func (ctx *Context) WriteString(s string) (int, error)

func (*Context) WriteXML

func (ctx *Context) WriteXML(v interface{}) (int, error)

func (*Context) Written

func (ctx *Context) Written() int64

func (*Context) WroteHeader

func (ctx *Context) WroteHeader() bool

type Handler

type Handler interface {
	ServeHTTP(*Context)
}

func NewAllowedMethods

func NewAllowedMethods(handle bool) Handler

func NewRedirectCleanedPath

func NewRedirectCleanedPath(permanent bool) Handler

func NewRedirectTrailingSlash

func NewRedirectTrailingSlash(permanent bool) Handler

type HandlerFunc

type HandlerFunc func(*Context)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(ctx *Context)

type Node

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

type Route

type Route struct {
	Name string
	// contains filtered or unexported fields
}

func Any

func Any(pattern string, handlers ...interface{}) *Route

func CONNECT

func CONNECT(pattern string, handlers ...interface{}) *Route

func DELETE

func DELETE(pattern string, handlers ...interface{}) *Route

func GET

func GET(pattern string, handlers ...interface{}) *Route
func HEAD(pattern string, handlers ...interface{}) *Route

func Handle

func Handle(method, pattern string, handlers ...interface{}) *Route

func OPTIONS

func OPTIONS(pattern string, handlers ...interface{}) *Route

func POST

func POST(pattern string, handlers ...interface{}) *Route

func PUT

func PUT(pattern string, handlers ...interface{}) *Route

func TRACE

func TRACE(pattern string, handlers ...interface{}) *Route

type Router

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

func (*Router) Any

func (r *Router) Any(path string, handlers ...interface{}) *Route

func (*Router) CONNECT

func (r *Router) CONNECT(path string, handlers ...interface{}) *Route

func (*Router) DELETE

func (r *Router) DELETE(path string, handlers ...interface{}) *Route

func (*Router) Fallback

func (r *Router) Fallback()

func (*Router) GET

func (r *Router) GET(path string, handlers ...interface{}) *Route

func (*Router) Group

func (r *Router) Group(path string, f func(*Router), handlers ...interface{})

func (*Router) HEAD

func (r *Router) HEAD(path string, handlers ...interface{}) *Route

func (*Router) Handle

func (r *Router) Handle(method, path string, handlers ...interface{}) *Route

func (*Router) Handler

func (r *Router) Handler() http.Handler

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handlers ...interface{}) *Route

func (*Router) POST

func (r *Router) POST(path string, handlers ...interface{}) *Route

func (*Router) PUT

func (r *Router) PUT(path string, handlers ...interface{}) *Route

func (*Router) TRACE

func (r *Router) TRACE(path string, handlers ...interface{}) *Route

func (*Router) Use

func (r *Router) Use(handlers ...interface{})

type Static

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

type Tag

type Tag struct {
	Kind byte
	Name string
	Rule *regexp.Regexp
}

func (Tag) Boundary

func (t Tag) Boundary(s string) (i int)

func (Tag) Same

func (t Tag) Same(x Tag) bool

func (Tag) String

func (t Tag) String() (s string)

type Tree

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

func (*Tree) ServeHTTP

func (t *Tree) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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