nice

package module
v0.0.0-...-55327a3 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2019 License: MIT Imports: 25 Imported by: 5

README

Nice

一个简单高效的Go Web及微服务开发框架。主要Web框架有路由、中间件,依赖注入和HTTP上下文构成,微服务主要有服务发现、分布式追踪等。

特性

  • 路由
  • 中间件
  • 依赖注入
  • 日志处理
  • 数据库操作
  • 缓存操作
  • 统一的HTTP错误处理
  • 微服务
    • 服务发现
    • 分布式追踪
  • ……

快速上手

安装
go get -u https://github.com/nic-chen/nice
代码
// nice.go
package main

import (
    "github.com/nic-chen/nice"
)

func main() {
    app := nice.Instance("")
    app.Get("/", func(c *nice.Context) {
        c.String(200, "Hello, World")
    })
    app.Run(":8080")
}
运行
go run nice.go
浏览
http://127.0.0.1:8080/
使用中间件
package main

import (
    "github.com/nic-chen/nice/middleware"
    "github.com/nic-chen/nice/middleware"
    "github.com/nic-chen/nice"
)

func main() {
    app := nice.Instance("")
    app.Use(middleware.Recovery())
    app.Use(middleware.Logger())

    app.Get("/", func(c *nice.Context) {
        c.String(200, "Hello, World")
    })

    app.Run(":8080")
}

示例

https://github.com/nic-chen/nice-example

我们构建了一个docker环境,你可以下载并直接运行示例: https://github.com/nic-chen/nice-example-docker

文档目录

Documentation

Index

Constants

View Source
const (

	// CharsetUTF8 ...
	CharsetUTF8 = "charset=utf-8"

	// MediaTypes
	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 (
	// DEV mode
	DEV = "development"
	// PROD mode
	PROD = "production"
	// TEST mode
	TEST = "test"
)
View Source
const (
	GET int = iota
	POST
	PUT
	DELETE
	PATCH
	OPTIONS
	HEAD
	// RouteLength route table length
	RouteLength
)

Variables

View Source
var (
	// ErrJSONPayloadEmpty is returned when the JSON payload is empty.
	ErrJSONPayloadEmpty = errors.New("JSON payload is empty")

	// ErrXMLPayloadEmpty is returned when the XML payload is empty.
	ErrXMLPayloadEmpty = errors.New("XML payload is empty")
)

Env default application runtime environment

View Source
var RouterMethodName = map[int]string{
	GET:     "GET",
	POST:    "POST",
	PUT:     "PUT",
	DELETE:  "DELETE",
	PATCH:   "PATCH",
	OPTIONS: "OPTIONS",
	HEAD:    "HEAD",
}

RouterMethodName declare method name with route table key

View Source
var RouterMethods = map[string]int{
	"GET":     GET,
	"POST":    POST,
	"PUT":     PUT,
	"DELETE":  DELETE,
	"PATCH":   PATCH,
	"OPTIONS": OPTIONS,
	"HEAD":    HEAD,
}

RouterMethods declare method key in route table

Functions

func IsParamChar

func IsParamChar(c byte) bool

IsParamChar check the char can used for route params a-z->65:90, A-Z->97:122, 0-9->48->57, _->95

func LoadConfig

func LoadConfig(yamlfile string) map[string]interface{}

加载配置 绝对路径

Types

type Cache

type Cache interface {
	Open()
	Close() error
	Do(command string, args ...interface{}) (interface{}, error)
}

type Context

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

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

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request, n *Nice) *Context

NewContext create a http context

func (*Context) Body

func (c *Context) Body() *RequestBody

Body get raw request body and return RequestBody

func (*Context) Break

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

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) GetUid

func (c *Context) GetUid() uint32

Get uid from context

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) IsAJAX

func (c *Context) IsAJAX() bool

IsAJAX returns if it is a ajax request

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) Nice

func (c *Context) Nice() *Nice

Nice get app instance

func (*Context) NotFound

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

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) ParamUint16

func (c *Context) ParamUint16(name string) uint16

ParamUint16 get route param from context and format to uint16

func (*Context) ParamUint32

func (c *Context) ParamUint32(name string) uint32

ParamUint32 get route param from context and format to uint32

func (*Context) ParamUint8

func (c *Context) ParamUint8(name string) uint8

ParamUint8 get route param from context and format to uint8

func (*Context) Params

func (c *Context) Params() map[string]string

Params returns route params from context

func (*Context) ParseForm

func (c *Context) ParseForm(maxSize int64) error

ParseForm parses a request body as multipart/form-data or parses the raw query from the URL and updates r.Form.

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

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) QueryJSON

func (c *Context) QueryJSON(v interface{}) error

QueryJSON decode json from http.Request.Body

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) QueryUint16

func (c *Context) QueryUint16(name string) uint16

QueryUint16 get a param from http.Request.Form and format to uint16

func (*Context) QueryUint32

func (c *Context) QueryUint32(name string) uint32

QueryUint32 get a param from http.Request.Form and format to uint32

func (*Context) QueryUint8

func (c *Context) QueryUint8(name string) uint8

QueryUint8 get a param from http.Request.Form and format to uint8

func (*Context) QueryXML

func (c *Context) QueryXML(v interface{}) error

QueryXML decode xml from http.Request.Body

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) Reset

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

Reset ...

func (*Context) RouteName

func (c *Context) RouteName() string

RouteName return context matched route name

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) SetUid

func (c *Context) SetUid(v uint32)

Set uid in context

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

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 nice

func (*DI) Get

func (d *DI) Get(name string) interface{}

Get fetch a di by name, return nil when name not set.

func (*DI) Set

func (d *DI) Set(name string, v interface{})

Set register a di nice dependency injection must be the special interface

type DIer

type DIer interface {
	Set(name string, v interface{})
	Get(name string) interface{}
}

DIer is an interface for nice dependency injection

func NewDI

func NewDI() DIer

NewDI create a DI instance

type Db

type Db interface {
	Close() error
	Query(sqlStr string, args ...interface{}) ([]map[string]interface{}, error)
	QueryRow(sqlStr string, args ...interface{}) *sql.Row
	Exec(sqlStr string, args ...interface{}) (sql.Result, error)
}

type ErrorHandleFunc

type ErrorHandleFunc func(error, *Context)

ErrorHandleFunc HTTP error handleFunc

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc context handler func

func WrapHandlerFunc

func WrapHandlerFunc(h HandlerFunc) HandlerFunc

WrapHandlerFunc wrap for context handler chain

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 nice

type Middleware

type Middleware interface{}

Middleware middleware handler

type Mysql

type Mysql struct {
	DriverName string
	Master     *sql.DB
	Slave      *sql.DB
	Loger      Logger
}

mysql is DB pool struct

func NewMysql

func NewMysql(config interface{}) *Mysql

Init DB pool

func (*Mysql) Begin

func (p *Mysql) Begin() (*SQLConnTransaction, error)

Begin transaction

func (*Mysql) Close

func (p *Mysql) Close() error

Close pool

func (*Mysql) Connect

func (p *Mysql) Connect(node MysqlNode, database, charset, MaxLifetime string) (*sql.DB, error)

func (*Mysql) Delete

func (p *Mysql) Delete(deleteStr string, args ...interface{}) (int64, error)

Delete via pool

func (*Mysql) Exec

func (p *Mysql) Exec(sqlStr string, args ...interface{}) (sql.Result, error)

func (*Mysql) Get

func (p *Mysql) Get(queryStr string, args ...interface{}) (map[string]interface{}, error)

Get via pool

func (*Mysql) Insert

func (p *Mysql) Insert(insertStr string, args ...interface{}) (int64, error)

Insert via pool

func (*Mysql) Query

func (p *Mysql) Query(sqlStr string, args ...interface{}) ([]map[string]interface{}, error)

Query via pool

func (*Mysql) QueryRow

func (p *Mysql) QueryRow(sqlStr string, args ...interface{}) *sql.Row

QueryRow via pool

func (*Mysql) Update

func (p *Mysql) Update(updateStr string, args ...interface{}) (int64, error)

Update via pool

type MysqlConf

type MysqlConf struct {
	//map类型
	Master      MysqlNode `yaml: "master"`
	Slave       MysqlNode `yaml: "slave"`
	Database    string    `yaml: "database"`
	Charset     string    `yaml: "charset"`
	MaxLifetime string    `yaml: "maxlifetime"`
}

type MysqlNode

type MysqlNode struct {
	Host     string `yaml: "host"`
	User     string `yaml: "user"`
	Password string `yaml: "password"`
	MaxOpen  int    `yaml: "maxopen"` //maxOpenConn
	MaxIdle  int    `yaml: "maxidle"` //maxIdleConn
}

type Nice

type Nice struct {
	Conf map[string]interface{}
	// contains filtered or unexported fields
}

Nice provlider an application

func Default

func Default() *Nice

Default initial a default app then returns

func Instance

func Instance(name string) *Nice

Instance register or returns named application

func New

func New() *Nice

New create a nice application without any config.

func (*Nice) Any

func (n *Nice) Any(pattern string, h ...HandlerFunc) RouteNode

Any is a shortcut for n.Router().handle("*", pattern, handlers)

func (*Nice) Cache

func (n *Nice) Cache() Cache

func (*Nice) Db

func (n *Nice) Db() Db

db

func (*Nice) Debug

func (n *Nice) Debug() bool

Debug returns nice debug state

func (*Nice) DefaultNotFoundHandler

func (n *Nice) DefaultNotFoundHandler(c *Context)

DefaultNotFoundHandler invokes the default HTTP error handler.

func (*Nice) Delete

func (n *Nice) Delete(pattern string, h ...HandlerFunc) RouteNode

Delete is a shortcut for n.Route(pattern, "DELETE", handlers)

func (*Nice) Error

func (n *Nice) Error(err error, c *Context)

Error execute internal error handler

func (*Nice) Get

func (n *Nice) Get(pattern string, h ...HandlerFunc) RouteNode

Get is a shortcut for n.Route(pattern, "GET", handlers)

func (*Nice) GetDI

func (n *Nice) GetDI(name string) interface{}

GetDI fetch a registered dependency injection

func (*Nice) Group

func (n *Nice) Group(pattern string, f func(), h ...HandlerFunc)

Group registers a list of same prefix route

func (*Nice) Head

func (n *Nice) Head(pattern string, h ...HandlerFunc) RouteNode

Head is a shortcut forn.Route(pattern, "Head", handlers)

func (*Nice) Logger

func (n *Nice) Logger() Logger

Logger return nice logger

func (*Nice) NotFound

func (n *Nice) NotFound(c *Context)

NotFound execute not found handler

func (*Nice) Options

func (n *Nice) Options(pattern string, h ...HandlerFunc) RouteNode

Options is a shortcut for n.Route(pattern, "Options", handlers)

func (*Nice) Patch

func (n *Nice) Patch(pattern string, h ...HandlerFunc) RouteNode

Patch is a shortcut for n.Route(pattern, "PATCH", handlers)

func (*Nice) Post

func (n *Nice) Post(pattern string, h ...HandlerFunc) RouteNode

Post is a shortcut for n.Route(pattern, "POST", handlers)

func (*Nice) Put

func (n *Nice) Put(pattern string, h ...HandlerFunc) RouteNode

Put is a shortcut for n.Route(pattern, "Put", handlers)

func (*Nice) Render

func (n *Nice) Render() Renderer

Render return nice render

func (*Nice) Route

func (n *Nice) Route(pattern, methods string, h ...HandlerFunc) RouteNode

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

Example:

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

func (*Nice) Router

func (n *Nice) Router() Router

Router return nice router

func (*Nice) Run

func (n *Nice) Run(addr string)

Run runs a server.

func (*Nice) RunServer

func (n *Nice) RunServer(s *http.Server)

RunServer runs a custom server.

func (*Nice) RunTLS

func (n *Nice) RunTLS(addr, certfile, keyfile string)

RunTLS runs a server with TLS configuration.

func (*Nice) RunTLSServer

func (n *Nice) RunTLSServer(s *http.Server, crtFile, keyFile string)

RunTLSServer runs a custom server with TLS configuration.

func (*Nice) ServeHTTP

func (n *Nice) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Nice) Server

func (n *Nice) Server(addr string) *http.Server

Server returns the internal *http.Server.

func (*Nice) SetAutoHead

func (n *Nice) 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 (*Nice) SetAutoTrailingSlash

func (n *Nice) SetAutoTrailingSlash(v bool)

SetAutoTrailingSlash optional trailing slash.

func (*Nice) SetDI

func (n *Nice) SetDI(name string, h interface{})

SetDI registers a dependency injection

func (*Nice) SetDIer

func (n *Nice) SetDIer(v DIer)

SetDIer set nice di

func (*Nice) SetDebug

func (n *Nice) SetDebug(v bool)

SetDebug set nice debug

func (*Nice) SetError

func (n *Nice) SetError(h ErrorHandleFunc)

SetError set error handler

func (*Nice) SetNotFound

func (n *Nice) SetNotFound(h HandlerFunc)

SetNotFound set not found route handler

func (*Nice) Static

func (n *Nice) Static(prefix string, dir string, index bool, h HandlerFunc)

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

func (*Nice) StaticFile

func (n *Nice) StaticFile(pattern string, path string) RouteNode

StaticFile shortcut for serve file

func (*Nice) URLFor

func (n *Nice) URLFor(name string, args ...interface{}) string

URLFor use named route return format url

func (*Nice) Use

func (n *Nice) Use(m ...Middleware)

Use registers a middleware

type Node

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

Node is struct for named route

func NewNode

func NewNode(pattern string, root *Tree) *Node

NewNode create a route node

func (*Node) Name

func (n *Node) Name(name string)

Name set name of route

type Redis

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

redis is RDS struct

func NewRedis

func NewRedis(config interface{}) *Redis

func (*Redis) Close

func (r *Redis) Close() error

Close pool

func (*Redis) Do

func (r *Redis) Do(command string, args ...interface{}) (interface{}, error)

Do commands

func (*Redis) Open

func (r *Redis) Open()

type RedisCnf

type RedisCnf struct {
	//map类型
	Master RedisNode `yaml:"master"`
	Slave  RedisNode `yaml:"slave"`
}

type RedisNode

type RedisNode struct {
	Host     string `yaml: "host"`
	Password string `yaml: "password"`
	Index    int    `yaml: "index"`
	MaxOpen  int    `yaml: "maxopen"` //maxOpenConn
	MaxIdle  int    `yaml: "maxidle"` //maxIdleConn
}

type Render

type Render struct {
}

Render default nice 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, tpl 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, n *Nice) *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

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

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(n []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 RouteNode

type RouteNode interface {
	Name(name string)
}

RouteNode is an router node

type Router

type Router interface {
	// 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.
	SetAutoHead(v bool)
	// SetAutoTrailingSlash optional trailing slash.
	SetAutoTrailingSlash(v bool)
	// Match find matched route then returns handlers and name
	Match(method, uri string, c *Context) ([]HandlerFunc, string)
	// URLFor use named route return format url
	URLFor(name string, args ...interface{}) string
	// Add registers a new handle with the given method, pattern and handlers.
	Add(method, pattern string, handlers []HandlerFunc) RouteNode
	// GroupAdd registers a list of same prefix route
	GroupAdd(pattern string, f func(), handlers []HandlerFunc)
	// Routes returns registered route uri in a string slice
	Routes() map[string][]string
	// NamedRoutes returns named route uri in a string slice
	NamedRoutes() map[string]string
}

Router is an router interface for nice

func NewTree

func NewTree(n *Nice) Router

NewTree create a router instance

type SQLConnTransaction

type SQLConnTransaction struct {
	SQLTX *sql.Tx
	Loger Logger
}

SQLConnTransaction is for transaction connection

func (*SQLConnTransaction) Commit

func (t *SQLConnTransaction) Commit() error

Commit transaction

func (*SQLConnTransaction) Delete

func (t *SQLConnTransaction) Delete(deleteStr string, args ...interface{}) (int64, error)

Delete via transaction

func (*SQLConnTransaction) Exec

func (t *SQLConnTransaction) Exec(sqlStr string, args ...interface{}) (sql.Result, error)

func (*SQLConnTransaction) Get

func (t *SQLConnTransaction) Get(queryStr string, args ...interface{}) (map[string]interface{}, error)

Get via transaction

func (*SQLConnTransaction) Insert

func (t *SQLConnTransaction) Insert(insertStr string, args ...interface{}) (int64, error)

Insert via transaction

func (*SQLConnTransaction) Query

func (t *SQLConnTransaction) Query(queryStr string, args ...interface{}) ([]map[string]interface{}, error)

Query via transaction

func (*SQLConnTransaction) Rollback

func (t *SQLConnTransaction) Rollback() error

Rollback transaction

func (*SQLConnTransaction) Update

func (t *SQLConnTransaction) Update(updateStr string, args ...interface{}) (int64, error)

Update via transaction

type Tree

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

Tree provlider router for nice with radix tree

func (*Tree) Add

func (t *Tree) Add(method, pattern string, handlers []HandlerFunc) RouteNode

Add registers a new handle with the given method, pattern and handlers. add check training slash option.

func (*Tree) GroupAdd

func (t *Tree) GroupAdd(pattern string, f func(), handlers []HandlerFunc)

GroupAdd add a group route has same prefix and handle chain

func (*Tree) Match

func (t *Tree) Match(method, pattern string, c *Context) ([]HandlerFunc, string)

Match find matched route then returns handlers and name

func (*Tree) NamedRoutes

func (t *Tree) NamedRoutes() map[string]string

NamedRoutes returns named route uri in a string slice

func (*Tree) Routes

func (t *Tree) Routes() map[string][]string

Routes returns registered route uri in a string slice

func (*Tree) SetAutoHead

func (t *Tree) 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 (*Tree) SetAutoTrailingSlash

func (t *Tree) SetAutoTrailingSlash(v bool)

SetAutoTrailingSlash optional trailing slash.

func (*Tree) URLFor

func (t *Tree) URLFor(name string, args ...interface{}) string

URLFor use named route return format url

Directories

Path Synopsis
A Default Config for example is below:
A Default Config for example is below:

Jump to

Keyboard shortcuts

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