baa

package module
v1.2.12 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2016 License: MIT Imports: 19 Imported by: 0

README

Baa GoDoc License Build Status Coverage Status

an express Go web framework with routing, middleware, dependency injection, http context.

Baa is no reflect, no regexp.

Getting Started

Install:

go get -u gopkg.in/baa.v1

Example:

package main

import (
    "gopkg.in/baa.v1"
)

func main() {
    app := baa.New()
    app.Get("/", func(c *baa.Context) {
        c.String(200, "Hello World!")
    })
    app.Run(":1323")
}

Features

  • route support static, param, group
  • route support handler chain
  • route support static file serve
  • middleware supoort handle chain
  • dependency injection support*
  • context support JSON/JSONP/XML/HTML response
  • centralized HTTP error handling
  • centralized log handling
  • whichever template engine support(emplement baa.Renderer)

Middlewares

Components

Performance

diff with the fast framework Echo

Note:

Echo use fasthttp in V2,here use Echo V1 for test。

Route Test

Based on [go-http-routing-benchmark] (https://github.com/safeie/go-http-routing-benchmark), Feb 27, 2016.

Baa route test is very close to Echo.

BenchmarkBaa_GithubAll          	   30000	     50984 ns/op	       0 B/op	       0 allocs/op
BenchmarkBeego_GithubAll        	    3000	    478556 ns/op	    6496 B/op	     203 allocs/op
BenchmarkEcho_GithubAll         	   30000	     47121 ns/op	       0 B/op	       0 allocs/op
BenchmarkGin_GithubAll          	   30000	     41004 ns/op	       0 B/op	       0 allocs/op
BenchmarkGocraftWeb_GithubAll   	    3000	    450709 ns/op	  131656 B/op	    1686 allocs/op
BenchmarkGorillaMux_GithubAll   	     200	   6591485 ns/op	  154880 B/op	    2469 allocs/op
BenchmarkMacaron_GithubAll      	    2000	    679559 ns/op	  201140 B/op	    1803 allocs/op
BenchmarkMartini_GithubAll      	     300	   5680389 ns/op	  228216 B/op	    2483 allocs/op
BenchmarkRevel_GithubAll        	    1000	   1413894 ns/op	  337424 B/op	    5512 allocs/op
HTTP Test
Code

Baa:

package main

import (
	"github.com/baa-middleware/logger"
	"github.com/baa-middleware/recovery"
	"gopkg.in/baa.v1"
)

func hello(c *baa.Context) {
	c.String(200, "Hello, World!\n")
}

func main() {
	b := baa.New()
	b.Use(logger.Logger())
	b.Use(recovery.Recovery())

	b.Get("/", hello)

	b.Run(":8001")
}

Echo:

package main

import (
	"github.com/labstack/echo"
	mw "github.com/labstack/echo/middleware"
)

// Handler
func hello(c *echo.Context) error {
	return c.String(200, "Hello, World!\n")
}

func main() {
	// Echo instance
	e := echo.New()

	// Middleware
	e.Use(mw.Logger())

	// Routes
	e.Get("/", hello)

	// Start server
	e.Run(":8001")
}
Result:

Baa http test is almost better than Echo.

Baa:

$ wrk -t 10 -c 100 -d 30 http://127.0.0.1:8001/
Running 30s test @ http://127.0.0.1:8001/
  10 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     1.92ms    1.43ms  55.26ms   90.86%
    Req/Sec     5.46k   257.26     6.08k    88.30%
  1629324 requests in 30.00s, 203.55MB read
Requests/sec:  54304.14
Transfer/sec:      6.78MB

Echo:

$ wrk -t 10 -c 100 -d 30 http://127.0.0.1:8001/
Running 30s test @ http://127.0.0.1:8001/
  10 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     2.83ms    3.76ms  98.38ms   90.20%
    Req/Sec     4.79k     0.88k   45.22k    96.27%
  1431144 requests in 30.10s, 178.79MB read
Requests/sec:  47548.11
Transfer/sec:      5.94MB

Use Cases

vodjk private projects.

Guide

godoc

document

Credits

Get inspirations from beego echo macaron

License

This project is under the MIT License (MIT) See the LICENSE file for the full license text.

Documentation

Overview

Package baa provides an express Go web framework.

package main

import (
    "github.com/go-baa/baa"
)

func main() {
    app := baa.New()
    app.Get("/", func(c *baa.Context) {
        c.String(200, "Hello World!")
    })
    app.Run(":8001")
}

Index

Constants

View Source
const (
	// DEV mode
	DEV = "development"
	// PROD mode
	PROD = "production"
	// TEST mode
	TEST = "test"
)
View Source
const (
	CharsetUTF8 = "charset=utf-8"

	ApplicationJSON                  = "application/json"
	ApplicationJSONCharsetUTF8       = ApplicationJSON + "; " + CharsetUTF8
	ApplicationJavaScript            = "application/javascript"
	ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
	ApplicationXML                   = "application/xml"
	ApplicationXMLCharsetUTF8        = ApplicationXML + "; " + CharsetUTF8
	ApplicationForm                  = "application/x-www-form-urlencoded"
	ApplicationProtobuf              = "application/protobuf"
	TextHTML                         = "text/html"
	TextHTMLCharsetUTF8              = TextHTML + "; " + CharsetUTF8
	TextPlain                        = "text/plain"
	TextPlainCharsetUTF8             = TextPlain + "; " + CharsetUTF8
	MultipartForm                    = "multipart/form-data"
)
View Source
const (
	// method key in routeMap
	GET int = iota
	POST
	PUT
	DELETE
	PATCH
	OPTIONS
	HEAD
	// RouteLength route table length
	RouteLength
)

Variables

Env default application runtime environment

Functions

This section is empty.

Types

type Baa

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

Baa provlider an application

func Default added in v1.2.10

func Default() *Baa

Default initial a default app then returns

func Instance added in v1.2.11

func Instance(name string) *Baa

Instance register or returns named application

func New

func New() *Baa

New create a baa application without any config.

func (*Baa) Any

func (b *Baa) Any(pattern string, h ...HandlerFunc) *Route

Any is a shortcut for b.router.handle("*", pattern, handlers)

func (*Baa) Debug

func (b *Baa) Debug() bool

Debug returns baa debug state

func (*Baa) DefaultNotFoundHandler

func (b *Baa) DefaultNotFoundHandler(c *Context)

DefaultNotFoundHandler invokes the default HTTP error handler.

func (*Baa) Delete

func (b *Baa) Delete(pattern string, h ...HandlerFunc) *Route

Delete is a shortcut for b.router.handle("DELETE", pattern, handlers)

func (*Baa) Error

func (b *Baa) Error(err error, c *Context)

Error execute internal error handler

func (*Baa) Get

func (b *Baa) Get(pattern string, h ...HandlerFunc) *Route

Get is a shortcut for b.router.handle("GET", pattern, handlers)

func (*Baa) GetDI

func (b *Baa) GetDI(name string) interface{}

GetDI fetch a registered dependency injection

func (*Baa) Group

func (b *Baa) Group(pattern string, f func(), h ...HandlerFunc)

Group registers a list of same prefix route

func (*Baa) Head

func (b *Baa) Head(pattern string, h ...HandlerFunc) *Route

Head is a shortcut for b.router.handle("HEAD", pattern, handlers)

func (*Baa) Logger

func (b *Baa) Logger() Logger

Logger return baa logger

func (*Baa) NotFound

func (b *Baa) NotFound(c *Context)

NotFound execute not found handler

func (*Baa) Options

func (b *Baa) Options(pattern string, h ...HandlerFunc) *Route

Options is a shortcut for b.router.handle("OPTIONS", pattern, handlers)

func (*Baa) Patch

func (b *Baa) Patch(pattern string, h ...HandlerFunc) *Route

Patch is a shortcut for b.router.handle("PATCH", pattern, handlers)

func (*Baa) Post

func (b *Baa) Post(pattern string, h ...HandlerFunc) *Route

Post is a shortcut for b.router.handle("POST", pattern, handlers)

func (*Baa) Put

func (b *Baa) Put(pattern string, h ...HandlerFunc) *Route

Put is a shortcut for b.router.handle("PUT", pattern, handlers)

func (*Baa) Render

func (b *Baa) Render() Renderer

Render return baa render

func (*Baa) Route

func (b *Baa) Route(pattern, methods string, h ...HandlerFunc) *Route

Route is a shortcut for same handlers but different HTTP methods.

Example:

baa.Route("/", "GET,POST", h)

func (*Baa) Run

func (b *Baa) Run(addr string)

Run runs a server.

func (*Baa) RunServer

func (b *Baa) RunServer(s *http.Server)

RunServer runs a custom server.

func (*Baa) RunTLS

func (b *Baa) RunTLS(addr, certfile, keyfile string)

RunTLS runs a server with TLS configuration.

func (*Baa) RunTLSServer

func (b *Baa) RunTLSServer(s *http.Server, crtFile, keyFile string)

RunTLSServer runs a custom server with TLS configuration.

func (*Baa) ServeHTTP

func (b *Baa) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Baa) Server

func (b *Baa) Server(addr string) *http.Server

Server returns the internal *http.Server.

func (*Baa) SetAutoHead

func (b *Baa) SetAutoHead(v bool)

SetAutoHead sets the value who determines whether add HEAD method automatically when GET method is added. Combo router will not be affected by this value.

func (*Baa) SetAutoTrailingSlash added in v1.2.8

func (b *Baa) SetAutoTrailingSlash(v bool)

SetAutoTrailingSlash optional trailing slash.

func (*Baa) SetDI

func (b *Baa) SetDI(name string, h interface{})

SetDI registers a dependency injection

func (*Baa) SetDebug

func (b *Baa) SetDebug(v bool)

SetDebug set baa debug

func (*Baa) SetError

func (b *Baa) SetError(h ErrorHandleFunc)

SetError set error handler

func (*Baa) SetNotFound added in v1.2.9

func (b *Baa) SetNotFound(h HandlerFunc)

SetNotFound set not found route handler

func (*Baa) Static

func (b *Baa) Static(prefix string, dir string, index bool, h HandlerFunc)

Static set static file route h used for set Expries ...

func (*Baa) URLFor

func (b *Baa) URLFor(name string, args ...interface{}) string

URLFor use named route return format url

func (*Baa) Use

func (b *Baa) Use(m ...Middleware)

Use registers a middleware

type Context

type Context struct {
	Req  *http.Request
	Resp *Response
	// contains filtered or unexported fields
}

Context provlider a HTTP context for baa context contains reqest, response, header, cookie and some content type.

func (*Context) Baa

func (c *Context) Baa() *Baa

Baa get app instance

func (*Context) Body

func (c *Context) Body() *RequestBody

Body get raw request body and return RequestBody

func (*Context) Break added in v1.2.4

func (c *Context) Break()

Break break the handles chain and Immediate return

func (*Context) DI

func (c *Context) DI(name string) interface{}

DI get registered dependency injection service

func (*Context) Error

func (c *Context) Error(err error)

Error invokes the registered HTTP error handler.

func (*Context) Fetch

func (c *Context) Fetch(tpl string) ([]byte, error)

Fetch render data by html template engine use context.store and returns data

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get returns data from context

func (*Context) GetCookie

func (c *Context) GetCookie(name string) string

GetCookie returns given cookie value from request header.

func (*Context) GetCookieBool

func (c *Context) GetCookieBool(name string) bool

GetCookieBool returns cookie result in float64 type.

func (*Context) GetCookieFloat64

func (c *Context) GetCookieFloat64(name string) float64

GetCookieFloat64 returns cookie result in float64 type.

func (*Context) GetCookieInt

func (c *Context) GetCookieInt(name string) int

GetCookieInt returns cookie result in int type.

func (*Context) GetCookieInt32 added in v1.2.12

func (c *Context) GetCookieInt32(name string) int32

GetCookieInt32 returns cookie result in int32 type.

func (*Context) GetCookieInt64

func (c *Context) GetCookieInt64(name string) int64

GetCookieInt64 returns cookie result in int64 type.

func (*Context) GetFile

func (c *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error)

GetFile returns information about user upload file by given form field name.

func (*Context) Gets

func (c *Context) Gets() map[string]interface{}

Gets returns data map from content store

func (*Context) HTML

func (c *Context) HTML(code int, tpl string)

HTML write render data by html template engine use context.store it is a alias of c.Render

func (*Context) IsMobile

func (c *Context) IsMobile() bool

IsMobile returns if it is a mobile phone device request

func (*Context) JSON

func (c *Context) JSON(code int, v interface{})

JSON write data by json format

func (*Context) JSONP

func (c *Context) JSONP(code int, callback string, v interface{})

JSONP write data by jsonp format

func (*Context) JSONString

func (c *Context) JSONString(v interface{}) (string, error)

JSONString return string by Marshal interface

func (*Context) Next

func (c *Context) Next()

Next execute next handler handle middleware first, last execute route handler if something wrote to http, break chain and return

func (*Context) NotFound added in v1.2.9

func (c *Context) NotFound()

NotFound invokes the registered HTTP NotFound handler.

func (*Context) Param

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

Param get route param from context

func (*Context) ParamBool

func (c *Context) ParamBool(name string) bool

ParamBool get route param from context and format to bool

func (*Context) ParamFloat

func (c *Context) ParamFloat(name string) float64

ParamFloat get route param from context and format to float64

func (*Context) ParamInt

func (c *Context) ParamInt(name string) int

ParamInt get route param from context and format to int

func (*Context) ParamInt32 added in v1.2.12

func (c *Context) ParamInt32(name string) int32

ParamInt32 get route param from context and format to int32

func (*Context) ParamInt64

func (c *Context) ParamInt64(name string) int64

ParamInt64 get route param from context and format to int64

func (*Context) Posts

func (c *Context) Posts() map[string]interface{}

Posts return http.Request form data

func (*Context) Query

func (c *Context) Query(name string) string

Query get a param from http.Request.Form

func (*Context) QueryBool

func (c *Context) QueryBool(name string) bool

QueryBool get a param from http.Request.Form and format to bool

func (*Context) QueryEscape

func (c *Context) QueryEscape(name string) string

QueryEscape returns escapred query result.

func (*Context) QueryFloat

func (c *Context) QueryFloat(name string) float64

QueryFloat get a param from http.Request.Form and format to float64

func (*Context) QueryInt

func (c *Context) QueryInt(name string) int

QueryInt get a param from http.Request.Form and format to int

func (*Context) QueryInt32 added in v1.2.12

func (c *Context) QueryInt32(name string) int32

QueryInt32 get a param from http.Request.Form and format to int32

func (*Context) QueryInt64

func (c *Context) QueryInt64(name string) int64

QueryInt64 get a param from http.Request.Form and format to int64

func (*Context) QueryStrings

func (c *Context) QueryStrings(name string) []string

QueryStrings get a group param from http.Request.Form and format to string slice

func (*Context) QueryTrim

func (c *Context) QueryTrim(name string) string

QueryTrim querys and trims spaces form parameter.

func (*Context) Querys

func (c *Context) Querys() map[string]interface{}

Querys return http.Request.URL queryString data

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect redirects the request using http.Redirect with status code.

func (*Context) Referer

func (c *Context) Referer() string

Referer returns http request Referer

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr returns more real IP address.

func (*Context) Render

func (c *Context) Render(code int, tpl string)

Render write render data by html template engine use context.store

func (*Context) SaveToFile

func (c *Context) SaveToFile(name, savePath string) error

SaveToFile reads a file from request by field name and saves to given path.

func (*Context) Set

func (c *Context) Set(key string, v interface{})

Set store data in context

func (*Context) SetCookie

func (c *Context) SetCookie(name string, value string, others ...interface{})

SetCookie sets given cookie value to response header. full params example: SetCookie(<name>, <value>, <max age>, <path>, <domain>, <secure>, <http only>)

func (*Context) SetParam

func (c *Context) SetParam(name, value string)

SetParam read route param value from uri

func (*Context) String

func (c *Context) String(code int, s string)

String write text by string

func (*Context) Text

func (c *Context) Text(code int, s []byte)

Text write text by []byte

func (*Context) URL added in v1.2.4

func (c *Context) URL(hasQuery bool) string

URL returns http request full url

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns http request UserAgent

func (*Context) XML

func (c *Context) XML(code int, v interface{})

XML sends an XML response with status code.

type DI

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

DI provlider a dependency injection service for baa

type ErrorHandleFunc

type ErrorHandleFunc func(error, *Context)

ErrorHandleFunc HTTP error handleFunc

type Handler

type Handler interface{}

Handler context handler

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc context handler func

type Logger

type Logger interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
}

Logger provlider a basic log interface for baa

type Middleware

type Middleware interface{}

Middleware middleware handler

type Render

type Render struct {
}

Render default baa template engine

func (*Render) Render

func (r *Render) Render(w io.Writer, tpl string, data interface{}) error

Render ...

type Renderer

type Renderer interface {
	Render(w io.Writer, name string, data interface{}) error
}

Renderer is the interface that wraps the Render method.

type RequestBody

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

RequestBody represents a request body.

func NewRequestBody

func NewRequestBody(r io.ReadCloser) *RequestBody

NewRequestBody ...

func (*RequestBody) Bytes

func (rb *RequestBody) Bytes() ([]byte, error)

Bytes reads and returns content of request body in bytes.

func (*RequestBody) ReadCloser

func (rb *RequestBody) ReadCloser() io.ReadCloser

ReadCloser returns a ReadCloser for request body.

func (*RequestBody) String

func (rb *RequestBody) String() (string, error)

String reads and returns content of request body in string.

type Response

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

Response implement ResponseWriter

func NewResponse

func NewResponse(w http.ResponseWriter, b *Baa) *Response

NewResponse ...

func (*Response) CloseNotify

func (r *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) GetWriter added in v1.2.9

func (r *Response) GetWriter() io.Writer

GetWriter returns response io writer

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example). To suppress implicit response headers, set their value to nil.

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) SetWriter added in v1.2.9

func (r *Response) SetWriter(w io.Writer)

SetWriter set response io writer

func (*Response) Size

func (r *Response) Size() int64

Size returns body size

func (*Response) Status

func (r *Response) Status() int

Status returns status code

func (*Response) Write

func (r *Response) Write(b []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

func (*Response) Wrote

func (r *Response) Wrote() bool

Wrote returns if writes something

type Route

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

Route is a tree node route use radix tree

func (*Route) Name

func (r *Route) Name(name string)

Name set name of route

type Router

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

Router provlider router for baa

Jump to

Keyboard shortcuts

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