ace

package module
v0.0.0-...-8ece619 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2016 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 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

ACE godoc badge gocover badge Build Status Go Report Card

Blazing fast Go Web Framework

image

####Installation

go get github.com/plimble/ace
Import
import "github.com/plimble/ace"

Performance

Ace is very fast you can see on this

Usage

Quick Start
a := ace.New()
a.GET("/:name", func(c *ace.C) {
	name := c.Param("name")
	c.JSON(200, map[string]string{"hello": name})
})
a.Run(":8080")

Default Middleware (Logger, Recovery)

a := ace.Default()
a.GET("/", func(c *ace.C) {
	c.String(200,"Hello ACE")
})
a.Run(":8080")
Router
a.DELETE("/", HandlerFunc)
a.HEAD("/", HandlerFunc)
a.OPTIONS("/", HandlerFunc)
a.PATCH("/", HandlerFunc)
a.PUT("/", HandlerFunc)
a.POST("/", HandlerFunc)
a.GET("/", HandlerFunc)
Example
a := ace.New()

a.GET("/", func(c *ace.C){
	c.String(200, "Hello world")
})

a.POST("/form/:id/:name", func(c *ace.C){
	id := c.Param("id")
	name := c.Param("name")
	age := c.Request.PostFormValue("age")
})

Response

JSON
data := struct{
	Name string `json:"name"`
}{
	Name: "John Doe",
}
c.JSON(200, data)
String
c.String(200, "Hello Ace")
Download
//application/octet-stream
c.Download(200, []byte("Hello Ace"))
HTML
c.HTML("index.html")
Redirect
c.Redirect("/home")

Group Router

g := a.Group("/people", func(c *ace.C) {
	fmt.Println("before route func")
	c.Next()
})

// /people/:name
g.GET("/:name", func(c *ace.C) {
	c.JSON(200, map[string]string{"TEST": "GET METHOD"})
})

// /people/:name
g.POST("/:name", func(c *ace.C) {
	c.JSON(200, map[string]string{"TEST": "POST METHOD"})
})

Data

Set/Get data in any HandlerFunc

a.Use(func(c *ace.C){
	c.SetData("isLogin", true)
})

a.Get("/", func(c *ace.C){
	isLogin := c.GetData("isLogin").(bool)
	//or get all data
	//c.GetAllData()
})

Get Post Form and Query

a.Get("/", func(c *ace.C){
	name := c.MustPostString(key, default_value)
	age := c.MustPostInt(key, d)

	q := c.MustQueryString(key, default_value)
	score := c.MustQueryFloat64(key, default_value)
})

Get data From JSON Request

a.Get("/", func(c *ace.C){
	user := struct{
		Name string `json:"name"`
	}{}

	c.ParseJSON(&user)
})

Panic Response

Use panic instead of if err != nil for response error

a.Get("/save", func(c *ace.C){
	user := &User{}

	c.ParseJSON(user)

	//this func return error
	//if error go to panic handler
	c.Panic(doSomething1(user))
	c.Panic(doSomething2(user))

	c.String(201, "created")
}

a.Get("/get", func(c *ace.C){
	id := c.Param("id")

	user, err := doSomeThing()
	//if error go to panic handler
	c.Panic(err)

	c.JSON(200, user)
}
Custom panic response
a := ace.New()
a.Panic(func(c *ace.C, rcv interface{}){
	switch err := rcv.(type) {
		case error:
			c.String(500, "%s\n%s", err, ace.Stack())
		case CustomError:
			log.Printf("%s\n%s", err, ace.Stack())
			c.JSON(err.Code, err.Msg)
	}
})

Middlewares

Ace middleware is implemented by custom handler

type HandlerFunc func(c *C)
Example
a := ace.New()
a.Use(ace.Logger())
Built-in Middlewares
Serve Static
a.Static("/assets", "./img")
Session

You can use store from sessions

import github.com/plimble/sessions/store/cookie

a := ace.New()

store := cookie.NewCookieStore()
a.Use(ace.Session(store, nil))

a.GET("/", func(c *ace.C) {
	//get session name
	session1 := c.Sessions("test")
	session1.Set("test1", "123")
	session1.Set("test2", 123)

	session2 := c.Sessions("foo")
	session2.Set("baz1", "123")
	session2.Set("baz2", 123)

	c.String(200, "")
})

a.GET("/test", func(c *C) {
	session := c.Sessions("test")
	//get value from key test1 if not found default value ""
	test1 := session.GetString("test1", "")
	test2 := session.GetInt("test2", 0)

	c.String(200, "")
})
Logger
a.Use(ace.Logger())

HTML Template Engine

Ace built on renderer interface. So you can use any template engine

type Renderer interface {
	Render(w http.ResponseWriter, name string, data interface{})
}
ACE Middlewares
Name Description
gzip GZIP compress
cors Enable Cross-origin resource sharing (CORS)
sessions Sessions
pongo2 Pongo2 Template Engine
csrf Cross Site Request Forgery protection
Contributing

If you'd like to help out with the project. You can put up a Pull Request.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetPool

func GetPool() *pool.BufferPool

func Stack

func Stack() []byte

stack returns a nicely formated stack frame, skipping skip frames

Types

type Ace

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

func Default

func Default() *Ace

Default server white recovery and logger middleware

func New

func New() *Ace

New server

func (*Ace) HtmlTemplate

func (a *Ace) HtmlTemplate(render Renderer)

HtmlTemplate use html template middleware

func (*Ace) Run

func (a *Ace) Run(addr string)

Run server with specific address and port

func (*Ace) RunTLS

func (a *Ace) RunTLS(addr string, cert string, key string)

RunTLS server with specific address and port

func (*Ace) ServeHTTP

func (a *Ace) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implement http.Handler

func (*Ace) SetPoolSize

func (a *Ace) SetPoolSize(poolSize int)

SetPoolSize of buffer

type C

type C struct {
	Request *http.Request
	Writer  ResponseWriter
	// contains filtered or unexported fields
}

C is context for every goroutine

func (*C) Abort

func (c *C) Abort()

Abort stop maddileware

func (*C) AbortWithStatus

func (c *C) AbortWithStatus(status int)

AbortWithStatus stop maddileware and return http status code

func (*C) ClientIP

func (c *C) ClientIP() string

ClientIP get ip from RemoteAddr

func (*C) Download

func (c *C) Download(status int, v []byte)

Download response with application/octet-stream; charset=UTF-8 Content type

func (*C) Get

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

Get data

func (*C) GetAll

func (c *C) GetAll() map[string]interface{}

GetAllData return all data

func (*C) HTML

func (c *C) HTML(name string, data interface{})

HTML render template engine

func (*C) HTTPLang

func (c *C) HTTPLang() string

HTTPLang get first language from HTTP Header

func (*C) JSON

func (c *C) JSON(status int, v interface{})

JSON response with application/json; charset=UTF-8 Content type

func (*C) MustPostFloat64

func (c *C) MustPostFloat64(key string, d float64) float64

func (*C) MustPostInt

func (c *C) MustPostInt(key string, d int) int

func (*C) MustPostString

func (c *C) MustPostString(key, d string) string

func (*C) MustPostStrings

func (c *C) MustPostStrings(key string, d []string) []string

func (*C) MustPostTime

func (c *C) MustPostTime(key string, layout string, d time.Time) time.Time

func (*C) MustQueryFloat64

func (c *C) MustQueryFloat64(key string, d float64) float64

func (*C) MustQueryInt

func (c *C) MustQueryInt(key string, d int) int

func (*C) MustQueryString

func (c *C) MustQueryString(key, d string) string

func (*C) MustQueryStrings

func (c *C) MustQueryStrings(key string, d []string) []string

func (*C) MustQueryTime

func (c *C) MustQueryTime(key string, layout string, d time.Time) time.Time

func (*C) Next

func (c *C) Next()

Next next middleware

func (*C) Panic

func (c *C) Panic(err error)

func (*C) Param

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

Param get param from route

func (*C) ParseJSON

func (c *C) ParseJSON(v interface{})

ParseJSON decode json to interface{}

func (*C) Redirect

func (c *C) Redirect(url string)

Redirect 302 response

func (*C) Sessions

func (c *C) Sessions(name string) *sessions.Session

func (*C) Set

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

Set data

func (*C) SetAll

func (c *C) SetAll(data map[string]interface{})

SetAll data

func (*C) String

func (c *C) String(status int, format string, val ...interface{})

String response with text/html; charset=UTF-8 Content type

type Context

type Context map[string]interface{}

type HandlerFunc

type HandlerFunc func(c *C)

func Logger

func Logger() HandlerFunc

NewLogger returns a new Logger instance

func Session

func Session(store sessions.Store, options *SessionOptions) HandlerFunc

Session use session middleware

type PanicHandler

type PanicHandler func(c *C, rcv interface{})

type Renderer

type Renderer interface {
	Render(w http.ResponseWriter, name string, data interface{})
}

Renderer html render interface

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether or not the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been written to. This is
	// useful for setting headers or any other operations that must happen before a response has been written.
	Before(func(ResponseWriter))
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

type Router

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

Router http router

func (*Router) DELETE

func (r *Router) DELETE(path string, handlers ...HandlerFunc)

DELETE handle DELETE method

func (*Router) GET

func (r *Router) GET(path string, handlers ...HandlerFunc)

GET handle GET method

func (*Router) Group

func (r *Router) Group(path string, handlers ...HandlerFunc) *Router

Group group route

func (*Router) HEAD

func (r *Router) HEAD(path string, handlers ...HandlerFunc)

HEAD handle HEAD method

func (*Router) HTTPHandlerFunc

func (r *Router) HTTPHandlerFunc(h http.HandlerFunc) HandlerFunc

HandlerFunc convert http.HandlerFunc to ace.HandlerFunc

func (*Router) Handle

func (r *Router) Handle(method, path string, handlers []HandlerFunc)

Handle handle with specific method

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handlers ...HandlerFunc)

OPTIONS handle OPTIONS method

func (*Router) PATCH

func (r *Router) PATCH(path string, handlers ...HandlerFunc)

PATCH handle PATCH method

func (*Router) POST

func (r *Router) POST(path string, handlers ...HandlerFunc)

POST handle POST method

func (*Router) PUT

func (r *Router) PUT(path string, handlers ...HandlerFunc)

PUT handle PUT method

func (*Router) Panic

func (r *Router) Panic(h PanicHandler)

Panic call when panic was called

func (*Router) RouteNotFound

func (r *Router) RouteNotFound(h HandlerFunc)

RouteNotFound call when route does not match

func (*Router) Static

func (r *Router) Static(path string, root http.Dir, handlers ...HandlerFunc)

Static server static file path is url path root is root directory

func (*Router) Use

func (r *Router) Use(middlewares ...HandlerFunc)

Use register middleware

type SessionOptions

type SessionOptions struct {
	Path   string
	Domain string
	// MaxAge=0 means no 'Max-Age' attribute specified.
	// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
	// MaxAge>0 means Max-Age attribute present and given in seconds.
	MaxAge   int
	Secure   bool
	HTTPOnly bool
}

SessionOptions session options

Jump to

Keyboard shortcuts

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