Documentation
¶
Index ¶
- Constants
- Variables
- func IsObjectIdHex(s string) bool
- type AppConfig
- type AppLogger
- type AppParams
- func (p *AppParams) Bson(v interface{}) error
- func (p *AppParams) File(name string) (multipart.File, *multipart.FileHeader, error)
- func (p *AppParams) Get(name string) string
- func (p *AppParams) Gob(v interface{}) error
- func (p *AppParams) HasForm(name string) bool
- func (p *AppParams) HasQuery(name string) bool
- func (p *AppParams) Json(v interface{}) error
- func (p *AppParams) Post(name string) string
- func (p *AppParams) Xml(v interface{}) error
- type AppRoute
- func (r *AppRoute) Any(path string, handler Middleware)
- func (r *AppRoute) DELETE(path string, handler Middleware)
- func (r *AppRoute) GET(path string, handler Middleware)
- func (r *AppRoute) Group(prefix string, middlewares ...Middleware) *AppRoute
- func (r *AppRoute) HEAD(path string, handler Middleware)
- func (r *AppRoute) Handle(method string, path string, handler Middleware)
- func (r *AppRoute) MockHandle(method string, path string, response http.ResponseWriter, handler Middleware)
- func (r *AppRoute) OPTIONS(path string, handler Middleware)
- func (r *AppRoute) PATCH(path string, handler Middleware)
- func (r *AppRoute) POST(path string, handler Middleware)
- func (r *AppRoute) PUT(path string, handler Middleware)
- func (r *AppRoute) Static(path, root string)
- func (r *AppRoute) Use(middlewares ...Middleware)
- type AppServer
- type Context
- func (c *Context) Abort()
- func (c *Context) AddHeader(key, value string)
- func (c *Context) Get(key string) (interface{}, bool)
- func (c *Context) GetFinal(key string) (interface{}, bool)
- func (c *Context) HasHeader(key string) bool
- func (c *Context) HasRawHeader(key string) bool
- func (c *Context) HashedReturn(hasher crypto.Hash, body ...interface{}) error
- func (c *Context) Header(key string) string
- func (c *Context) Json(data interface{}) error
- func (c *Context) JsonP(callback string, data interface{}) error
- func (c *Context) MustGet(key string) interface{}
- func (c *Context) MustGetFinal(key string) interface{}
- func (c *Context) MustSetFinal(key string, value interface{})
- func (c *Context) Next()
- func (c *Context) RawHeader(key string) string
- func (c *Context) Redirect(location string)
- func (c *Context) Render(w Render, data interface{}) error
- func (c *Context) RequestID() string
- func (c *Context) RequestURI() string
- func (c *Context) Return(body ...interface{}) error
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetFinal(key string, value interface{}) error
- func (c *Context) SetHeader(key, value string)
- func (c *Context) SetStatus(code int)
- func (c *Context) Text(data interface{}) error
- func (c *Context) Xml(data interface{}) error
- type DefaultRender
- type HashRender
- type JsonRender
- type JsonpRender
- type Logger
- type LoggerConfig
- type Middleware
- type ObjectId
- type Render
- type Response
- func (r *Response) Before(filter func(w Responser))
- func (r *Response) Flush()
- func (r *Response) FlushHeader()
- func (r *Response) HeaderFlushed() bool
- func (r *Response) Size() int
- func (r *Response) Status() int
- func (r *Response) Write(data []byte) (size int, err error)
- func (r *Response) WriteHeader(code int)
- type ResponseFilter
- type Responser
- type RunMode
- type SectionConfig
- type ServerConfig
- type StatusCoder
- type TextRender
- type XmlRender
Constants ¶
const ( Development RunMode = "development" Test RunMode = "test" Production RunMode = "production" DefaultMaxMultiformBytes = 32 << 20 // 32M DefaultMaxHeaderBytes = 64 << 10 // 64k DefaultHttpRequestId = "X-Request-Id" DefaultHttpRequestTimeout = 30 // 30s DefaultHttpResponseTimeout = 30 // 30s )
Variables ¶
var ( DefaultServerConfig = &ServerConfig{ Addr: "127.0.0.1", Port: 9090, Ssl: false, RequestId: DefaultHttpRequestId, } DefaultLoggerConfig = &LoggerConfig{ Output: "stderr", LevelName: "info", } DefaultSectionConfig = &SectionConfig{ Server: DefaultServerConfig, Logger: DefaultLoggerConfig, } )
var ( ErrHeaderFlushed = errors.New("Response headers have been written!") ErrConfigSection = errors.New("Config section does not exist!") ErrSettingsKey = errors.New("Settings key is duplicated!") ErrHash = errors.New("The hash function does not linked into the binary!") )
var ( // FindModeConfigFile returns config file for specified run mode. // You could custom your own run mode config file by overwriting. FindModeConfigFile = func(runMode, srcPath string) string { srcPath = path.Clean(srcPath) filename := "application.json" switch RunMode(runMode) { case Development: filename = "application.development.json" case Test: filename = "application.test.json" case Production: } file := path.Join(srcPath, "config", filename) if _, err := os.Stat(file); os.IsNotExist(err) { file = path.Join(srcPath, "config", "application.json") } return file } )
Functions ¶
func IsObjectIdHex ¶
IsObjectIdHex returns whether s is a valid hex representation of an ObjectId. See the ObjectIdHex function.
Types ¶
type AppConfig ¶
type AppConfig struct { Mode RunMode `json:"mode"` Name string `json:"name"` Sections map[RunMode]*json.RawMessage `json:"sections"` }
func NewAppConfig ¶
NewAppConfig returns app config by parsing application.json
func NewStringAppConfig ¶
NewStringAppConfig returns app config by parsing json string
func (*AppConfig) Section ¶
func (config *AppConfig) Section() *SectionConfig
Section is shortcut of retreving app server and logger configurations at one time It returns SectionConfig if exists, otherwise returns DefaultSectionConfig instead
func (*AppConfig) UnmarshalJSON ¶
UnmarshalJSON parses JSON-encoded data of section and stores the result in the value pointed to by v. It returns ErrConfigSection error if section of the current mode does not exist.
type AppLogger ¶
AppLogger implements Logger interface
func NewAppLogger ¶
type AppParams ¶
type AppParams struct {
// contains filtered or unexported fields
}
func NewAppParams ¶
func NewAppParams(r *http.Request, params httprouter.Params) *AppParams
func (*AppParams) Get ¶
Get returns the first value for the named component of the request. NOTE: httprouter.Params takes precedence over URL query string values.
type AppRoute ¶
type AppRoute struct { Handlers []Middleware // contains filtered or unexported fields }
func NewAppRoute ¶
NewAppRoute creates a new app route with specified prefix and server
func (*AppRoute) Any ¶
func (r *AppRoute) Any(path string, handler Middleware)
Any is a shortcut for all request methods
func (*AppRoute) DELETE ¶
func (r *AppRoute) DELETE(path string, handler Middleware)
DELETE is a shortcut of route.Handle("DELETE", path, handler)
func (*AppRoute) GET ¶
func (r *AppRoute) GET(path string, handler Middleware)
GET is a shortcut of route.Handle("GET", path, handler)
func (*AppRoute) Group ¶
func (r *AppRoute) Group(prefix string, middlewares ...Middleware) *AppRoute
Group returns a new app route group which has the same prefix path and middlewares
func (*AppRoute) HEAD ¶
func (r *AppRoute) HEAD(path string, handler Middleware)
HEAD is a shortcut of route.Handle("HEAD", path, handler)
func (*AppRoute) Handle ¶
func (r *AppRoute) Handle(method string, path string, handler Middleware)
Handle registers a new resource with its handler
func (*AppRoute) MockHandle ¶
func (r *AppRoute) MockHandle(method string, path string, response http.ResponseWriter, handler Middleware)
MockHandle mocks a new resource with specified response and handler, useful for testing
func (*AppRoute) OPTIONS ¶
func (r *AppRoute) OPTIONS(path string, handler Middleware)
OPTIONS is a shortcut of route.Handle("OPTIONS", path, handler)
func (*AppRoute) PATCH ¶
func (r *AppRoute) PATCH(path string, handler Middleware)
PATCH is a shortcut of route.Handle("PATCH", path, handler)
func (*AppRoute) POST ¶
func (r *AppRoute) POST(path string, handler Middleware)
POST is a shortcut of route.Handle("POST", path, handler)
func (*AppRoute) PUT ¶
func (r *AppRoute) PUT(path string, handler Middleware)
PUT is a shortcut of route.Handle("PUT", path, handler)
func (*AppRoute) Use ¶
func (r *AppRoute) Use(middlewares ...Middleware)
Use registers new middlewares to the route TODO: ignore duplicated middlewares?
type AppServer ¶
type AppServer struct { *AppRoute // contains filtered or unexported fields }
func NewWithLogger ¶
NewWithLogger creates application server with provided Logger
func (*AppServer) Clean ¶
func (s *AppServer) Clean()
Clean removes all registered middlewares, it useful in testing cases.
func (*AppServer) ServeHTTP ¶
func (s *AppServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface
func (*AppServer) Use ¶
func (s *AppServer) Use(middlewares ...Middleware)
Use applies middlewares to app route NOTE: It dispatch to Route.Use by overwrite
type Context ¶
type Context struct { Response Responser Request *http.Request Params *AppParams Server *AppServer Config *AppConfig Logger Logger // contains filtered or unexported fields }
func NewContext ¶
func (*Context) HasHeader ¶
HasHeader returns true if request sets its header for canonicaled specified key
func (*Context) HasRawHeader ¶
HasRawHeader returns true if request sets its header with specified key
func (*Context) HashedReturn ¶
HashedReturn returns response with ETag header calculated hash of response.Body dynamically
func (*Context) Json ¶
Json returns response with json codec and Content-Type: application/json header
func (*Context) JsonP ¶
JsonP returns response with json codec and Content-Type: application/javascript header
func (*Context) MustGetFinal ¶
MustGetFinal returns a frozen value of key or panic when key doesn't exist
func (*Context) MustSetFinal ¶
MustSetFinal associates a value with key for the context and freezes following update, it panics if key is duplicated.
func (*Context) Next ¶
func (c *Context) Next()
Next executes the remain handlers in the chain. NOTE: It ONLY used in the middlewares!
func (*Context) RequestURI ¶
RequestURI returns request raw uri
func (*Context) SetFinal ¶
SetFinal associates a value with key for the context and freezes following update
type DefaultRender ¶
type DefaultRender struct {
// contains filtered or unexported fields
}
DefaultRender responses with default Content-Type header
func (*DefaultRender) ContentType ¶
func (render *DefaultRender) ContentType() string
func (*DefaultRender) Render ¶
func (render *DefaultRender) Render(v interface{}) error
type HashRender ¶
type HashRender struct {
// contains filtered or unexported fields
}
HashRender responses with Etag header calculated from render data dynamically. NOTE: This always write response by copy if the render data is an io.Reader!!!
func (*HashRender) ContentType ¶
func (render *HashRender) ContentType() string
func (*HashRender) Render ¶
func (render *HashRender) Render(v interface{}) error
type JsonRender ¶
type JsonRender struct {
// contains filtered or unexported fields
}
JsonRender responses with Content-Type: application/json header It transform response data by json.Marshal.
func (*JsonRender) ContentType ¶
func (render *JsonRender) ContentType() string
func (*JsonRender) Render ¶
func (render *JsonRender) Render(v interface{}) error
type JsonpRender ¶
type JsonpRender struct {
// contains filtered or unexported fields
}
JsonpRender responses with Content-Type: application/javascript header It transform response data by json.Marshal.
func (*JsonpRender) ContentType ¶
func (render *JsonpRender) ContentType() string
func (*JsonpRender) Render ¶
func (render *JsonpRender) Render(v interface{}) error
type Logger ¶
type Logger interface { New(requestId string) Logger RequestId() string SetLevelByName(level string) error SetColor(color bool) Print(v ...interface{}) Printf(format string, v ...interface{}) Debug(v ...interface{}) Debugf(format string, v ...interface{}) Info(v ...interface{}) Infof(format string, v ...interface{}) Warn(v ...interface{}) Warnf(format string, v ...interface{}) Error(v ...interface{}) Errorf(format string, v ...interface{}) Fatal(v ...interface{}) Fatalf(format string, v ...interface{}) Panic(v ...interface{}) Panicf(format string, v ...interface{}) }
Logger defines interface of application log apis.
type LoggerConfig ¶
type LoggerConfig struct { Output string `json:"output"` // valid values [stdout|stderr|null|path/to/file] LevelName string `json:"level"` // valid values [debug|info|warn|error] FilterParams []string `json:"filter_params"` }
logger config spec
func (*LoggerConfig) Level ¶
func (l *LoggerConfig) Level() logger.Level
type Middleware ¶
type Middleware func(ctx *Context)
Middleware represents request filters and resource handler NOTE: It is the filter's responsibility to invoke ctx.Next() for chainning.
type ObjectId ¶
type ObjectId string
ObjectId is a unique ID identifying a BSON value. It must be exactly 12 bytes long. MongoDB objects by default have such a property set in their "_id" property.
http://www.mongodb.org/display/DOCS/Object+IDs
func NewObjectIdWithTime ¶
NewObjectIdWithTime returns a dummy ObjectId with the timestamp part filled with the provided number of seconds from epoch UTC, and all other parts filled with zeroes. It's not safe to insert a document with an id generated by this method, it is useful only for queries to find documents with ids generated before or after the specified timestamp.
func ObjectIdHex ¶
ObjectIdHex returns an ObjectId from the provided hex representation. Calling this function with an invalid hex representation will cause a runtime panic. See the IsObjectIdHex function.
func (ObjectId) Counter ¶
Counter returns the incrementing value part of the id. It's a runtime error to call this method with an invalid id.
func (ObjectId) Machine ¶
Machine returns the 3-byte machine id part of the id. It's a runtime error to call this method with an invalid id.
func (ObjectId) Pid ¶
Pid returns the process id part of the id. It's a runtime error to call this method with an invalid id.
func (ObjectId) String ¶
String returns a hex string representation of the id. Example: ObjectIdHex("4d88e15b60f486e428412dc9").
type Render ¶
Render represents HTTP response render
func NewDefaultRender ¶
func NewJsonRender ¶
func NewJsonpRender ¶
func NewTextRender ¶
func NewXmlRender ¶
type Response ¶
type Response struct { http.ResponseWriter // contains filtered or unexported fields }
func (*Response) FlushHeader ¶
func (r *Response) FlushHeader()
FlushHeader writes response headers with status and reset size, it also invoke before filters
func (*Response) HeaderFlushed ¶
HeaderFlushed returns whether response headers has written
func (*Response) WriteHeader ¶
WriteHeader sets response status code only by overwrites underline
type ResponseFilter ¶
type ResponseFilter func(Responser)
type Responser ¶
type Responser interface { http.ResponseWriter http.Flusher Before(filter func(w Responser)) // register before filter Size() int // return the size of response body Status() int // response status code HeaderFlushed() bool // whether response header has been sent? FlushHeader() // send response header }
Responser represents HTTP response interface
func NewResponse ¶
func NewResponse(w http.ResponseWriter) Responser
type SectionConfig ¶
type SectionConfig struct { Server *ServerConfig `json:"server"` Logger *LoggerConfig `json:"logger"` }
app server and logger config
type ServerConfig ¶
type ServerConfig struct { Addr string `json:"addr"` Port int `json:"port"` RTimeout int `json:"request_timeout"` // time in s WTimeout int `json:"response_timeout"` // time in s MaxHeaderBytes int `json:"max_header_bytes"` Ssl bool `json:"ssl"` SslCert string `json:"ssl_cert"` SslKey string `json:"ssl_key"` Throttle int `json:"throttle"` // in time.Second/throttle ms SlowdownMs int `json:"slowdown_ms"` // in ms RequestId string `json:"request_id"` }
server config spec
type StatusCoder ¶
type StatusCoder interface {
StatusCode() int
}
StatusCoder represents HTTP response status code
type TextRender ¶
type TextRender struct {
// contains filtered or unexported fields
}
TextRender responses with Content-Type: text/plain header It transform response data by stringify.
func (*TextRender) ContentType ¶
func (render *TextRender) ContentType() string
func (*TextRender) Render ¶
func (render *TextRender) Render(v interface{}) error
type XmlRender ¶
type XmlRender struct {
// contains filtered or unexported fields
}
XmlRender responses with Content-Type: text/xml header It transform response data by xml.Marshal.