ace

package module
v0.0.0-...-11dc724 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2020 License: Apache-2.0 Imports: 21 Imported by: 0

README

ACE

godoc badge Build Status Go Report Card Coverage Status

Blazing fast Go Web Framework, originally by plimble, but went unmaintained, so we hope to give it a second life here.

Installation

This library is compatible with Go Modules, so you can simply run go mod update -add github.com/contentway/ace

go get github.com/contentway/ace
Import
import "github.com/contentway/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/contentway/ace/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

View Source
const (
	// 2xx status codes
	StatusOK       = 200
	StatusCreated  = 201
	StatusAccepted = 202

	// 4xx status codes
	StatusBadRequest                  = 400
	StatusUnauthorized                = 401
	StatusPaymentRequired             = 402
	StatusForbidden                   = 403
	StatusNotFound                    = 404
	StatusMethodNotAllowed            = 405
	StatusNotAcceptable               = 406
	StatusProxyAuthenticationRequired = 407
	StatusRequestTimeout              = 408
	StatusConflict                    = 409
	StatusGone                        = 410
	StatusLengthRequired              = 411
	StatusPreconditionFailed          = 412
	StatusRequestEntityTooLarge       = 413
	StatusURITooLong                  = 414
	StatusUnsupportedMediaType        = 415
	StatusRangeNotSatisfiable         = 416
	StatusExpectationFailed           = 417
	StatusImATeapot                   = 418
	StatusUnprocessableEntity         = 422
	StatusLocked                      = 423

	// 5xx status codes
	StatusInternalServerError = 500
	StatusNotImplemented      = 501
	StatusBadGateway          = 502
	StatusServiceUnavailable  = 503
	StatusGatewayTimeout      = 504

	HeaderAuthorization      = "Authorization"
	HeaderContentType        = "Content-Type"
	HeaderContentDisposition = "Content-Disposition"

	AbortMiddlewareIndex = math.MaxInt8 / 2
)

Variables

This section is empty.

Functions

func FileExists

func FileExists(filePath string) bool

File exists returns whether or not the filePath exists and is a file

func HandleServeFileFallback

func HandleServeFileFallback(basePath string, fallbackFilePath string) func(c *C)

HandleServeFileFallback is a helper method that generates a HTTP handler func. The handler will try to serve the requested URL, starting from basePath, and will otherwise serve the file located at fallbackFilePath if the requested file wasn't found in the first place. This effectively acts like nginx try_files, or Apache's RewriteCond XX -f.

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 with recovery and logger middleware. Used for Unit Testing.

func New

func New() *Ace

func (*Ace) HtmlTemplate

func (a *Ace) HtmlTemplate(render Renderer)

HtmlTemplate sets the renderer to use for HTML templates

func (*Ace) Run

func (a *Ace) Run(addr string)

Run ace with specific address and port

func (*Ace) RunTLS

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

RunTLS ace with specific address, port and TLS certificates

func (*Ace) ServeHTTP

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

ServeHTTP serves a request locally as if it was handled by the HTTP ace

func (*Ace) SetPoolSize

func (a *Ace) SetPoolSize(poolSize int)

SetPoolSize defines the number of write buffers we should keep

type C

type C struct {
	Request *http.Request

	Writer ResponseWriter
	// contains filtered or unexported fields
}

func (*C) Abort

func (c *C) Abort()

Abort stops the middleware chain

func (*C) AbortWithStatus

func (c *C) AbortWithStatus(status int)

AbortWithStatus stops the middleware chain and return the specified HTTP status code

func (*C) AddHeader

func (c *C) AddHeader(key string, value string)

AddHeader adds an header to the response

func (*C) ClientIP

func (c *C) ClientIP() string

ClientIP returns the remote IP address, without port. See ClientRemoteAddress for source IP and port.

func (*C) ClientRemoteAddress

func (c *C) ClientRemoteAddress() string

ClientRemoteAddress returns the remote IP address and port

func (*C) Download

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

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

func (*C) DownloadStream

func (c *C) DownloadStream(status int, filename string, v io.Reader)

DownloadStream response with application/octet-stream, but reading from a io.Reader

func (*C) File

func (c *C) File(status int, filePath string)

File responds a file with text/html content type from a specified file path

func (*C) FormData

func (c *C) FormData() (url.Values, error)

func (*C) FormFile

func (c *C) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

func (*C) Get

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

Get retrieves data previously stored in this context using C.Set() or C.SetAll().

func (*C) GetAll

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

GetAll returns all the data previously stored in this context using C.Set() or C.SetAll().

func (*C) JSON

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

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

func (*C) MultipartFormData

func (c *C) MultipartFormData() (*multipart.Form, error)

func (*C) Next

func (c *C) Next()

Next runs the next HandlerFunc in the stack (ie. the next middleware)

func (*C) Param

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

Param returns a parameter value from the route

func (*C) ParseJSON

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

ParseJSON decodes json to interface{}

func (*C) QueryString

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

QueryString returns a param value from the URL GET parameters, where "key" is the parameter key, and "d" is the default value when the key isn't set in the current request.

func (*C) QueryStringArray

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

QueryString returns a param array from the URL GET parameters, where "key" is the parameter key, and "d" is the default value when the key isn't set in the current request.

func (*C) QueryStringInteger

func (c *C) QueryStringInteger(key string, d int64) int64

QueryStringInteger returns a param value from the URL GET parameters, where "key" is the parameter key, and "d" is the default value when the key isn't set in the current request, or if the value is not a valid integer..

func (*C) Sessions

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

Sessions returns the sessions with the provided name

func (*C) Set

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

Set stores arbitrary data inside this context to re-use in handlers

func (*C) SetAll

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

SetAll stores and erases the existing data inside this context. See C.Set().

func (*C) SetHeader

func (c *C) SetHeader(key string, value string)

SetHeader replaces and sets an header to the response

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 is the caller method that returns a Session middleware HandlerFunc

type PanicHandler

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

type Renderer

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

Renderer is the interface that lets you use any HTML renderer

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 groups routes together onto a same path prefix

func (*Router) HEAD

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

HEAD handle HEAD method

func (*Router) Handle

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

Handle handle with specific method

func (*Router) HandlerFunc

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

HandlerFunc converts http.HandlerFunc to our own HandlerFunc

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 is the handler called when the panic() function is called

func (*Router) RouteNotFound

func (r *Router) RouteNotFound(h HandlerFunc)

RouteNotFound is called call when no route match

func (*Router) Static

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

Static serves a static path, where path is the URL path and root is the root directory to serve from that path

func (*Router) Use

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

Use registers a 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 are the options of the browser session

Directories

Path Synopsis
package pool is originally from github.com/plimble/utils/pool
package pool is originally from github.com/plimble/utils/pool

Jump to

Keyboard shortcuts

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