Documentation ¶
Index ¶
- Constants
- Variables
- func IsGIDHex(s string) bool
- type AppConfig
- type AppLogger
- type AppParams
- func (p *AppParams) File(name string) (multipart.File, *multipart.FileHeader, error)
- func (p *AppParams) Get(name string) string
- func (p *AppParams) GetBool(name string) (bool, error)
- func (p *AppParams) GetFloat(name string) (float64, error)
- func (p *AppParams) GetInt(name string) (int, error)
- func (p *AppParams) GetInt16(name string) (int16, error)
- func (p *AppParams) GetInt32(name string) (int32, error)
- func (p *AppParams) GetInt64(name string) (int64, error)
- func (p *AppParams) GetInt8(name string) (int8, error)
- func (p *AppParams) GetUint16(name string) (uint16, error)
- func (p *AppParams) GetUint32(name string) (uint32, error)
- func (p *AppParams) GetUint64(name string) (uint64, error)
- func (p *AppParams) GetUint8(name string) (uint8, error)
- 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) RawBody() ([]byte, error)
- func (p *AppParams) Xml(v interface{}) error
- type AppRoute
- func (r *AppRoute) Any(path string, handler Middleware)
- func (r *AppRoute) CleanModdilewares()
- 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, uri string, handler Middleware)
- func (r *AppRoute) Handler(method, uri string, handler http.Handler)
- func (r *AppRoute) HandlerFunc(method, uri string, handler http.HandlerFunc)
- func (r *AppRoute) Middlewares() []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) ProxyHandle(method string, path string, proxy *httputil.ReverseProxy, ...)
- func (r *AppRoute) Resource(resource string, controller interface{}) *AppRoute
- func (r *AppRoute) ServeHTTP(resp http.ResponseWriter, req *http.Request)
- func (r *AppRoute) SetHandler(handler Handler)
- func (r *AppRoute) Static(path, root string)
- func (r *AppRoute) Use(middlewares ...Middleware)
- type AppServer
- type Configer
- type Context
- func (c *Context) Abort()
- func (c *Context) Action() string
- func (c *Context) AddHeader(key, value string)
- func (c *Context) Controller() string
- func (c *Context) Get(key string) (v interface{}, ok bool)
- func (c *Context) GetFinal(key string) (v interface{}, ok 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 ContextHandle
- type ControllerCreate
- type ControllerDestroy
- type ControllerDispatch
- type ControllerExplore
- type ControllerID
- type ControllerIndex
- type ControllerShow
- type ControllerUpdate
- type DefaultRender
- type FakeHandle
- type GID
- type Handler
- type HashRender
- type JsonRender
- type JsonpRender
- type Logger
- type LoggerConfig
- type Middleware
- type Render
- type Response
- func (r *Response) Before(filter ResponseFilter)
- func (r *Response) Flush()
- func (r *Response) FlushHeader()
- func (r *Response) HeaderFlushed() bool
- func (r *Response) Reset(w http.ResponseWriter)
- 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 ( DefaultMaxMultiformBytes = 32 << 20 // 32M DefaultMaxHeaderBytes = 64 << 10 // 64k )
http config
const ( DefaultHttpRequestID = "X-Request-Id" DefaultMaxHttpRequestIDLen = 32 DefaultHttpRequestTimeout = 30 // 30s DefaultHttpResponseTimeout = 30 // 30s )
server config
const ( RenderDefaultContentType = "text/plain; charset=utf-8" RenderJsonContentType = "application/json" RenderJsonPContentType = "application/javascript" RednerXmlContentType = "text/xml" )
const (
SchemaConfig = "gogo://config"
)
internal schema
Variables ¶
var ( DefaultServerConfig = &ServerConfig{ Addr: "127.0.0.1", Port: 9090, Ssl: false, RequestID: DefaultHttpRequestID, } DefaultLoggerConfig = &LoggerConfig{ Output: "stderr", LevelName: "info", FilterFields: []string{"password", "token"}, } 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) finfo, ferr := os.Stat(srcPath) if ferr != nil { return SchemaConfig } if !finfo.IsDir() && (finfo.Mode()&os.ModeSymlink == 0) { return 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 ¶
Types ¶
type AppConfig ¶
type AppConfig struct { Mode RunMode `json:"mode"` Name string `json:"name"` Sections map[RunMode]*json.RawMessage `json:"sections"` }
AppConfig defines config component of gogo It implements Configer interface
func NewAppConfig ¶
NewAppConfig returns *AppConfig by parsing application.json
func NewAppConfigFromDefault ¶
NewAppConfigFromDefault returns *AppConfig of defaults
func NewAppConfigFromString ¶
NewAppConfigFromString returns *AppConfig 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 defines log component of gogo, it implements Logger interface with pool support
func NewAppLogger ¶
NewAppLogger returns *AppLogger inited with args
func (*AppLogger) New ¶
New returns a new Logger with provided requestID which shared writer with current logger
type AppParams ¶
type AppParams struct {
// contains filtered or unexported fields
}
AppParams defines params component of gogo
func NewAppParams ¶
func NewAppParams(r *http.Request, params httpdispatch.Params) *AppParams
NewAppParams returns an *AppParams with *http.Request and httpdispatch.Params
func (*AppParams) Get ¶
Get returns the first value for the named component of the request. NOTE: httpdispatch.Params takes precedence over URL query string values.
func (*AppParams) Post ¶
Post returns the named comonent of the request by calling http.Request.FormValue()
type AppRoute ¶
type AppRoute struct {
// contains filtered or unexported fields
}
AppRoute defines route component of gogo
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) CleanModdilewares ¶
func (r *AppRoute) CleanModdilewares()
CleanModdilewares removes all registered middlewares of AppRoute NOTE: it's useful in testing cases.
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 *AppRoute 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, uri string, handler Middleware)
Handle registers a new resource by Middleware
func (*AppRoute) HandlerFunc ¶
func (r *AppRoute) HandlerFunc(method, uri string, handler http.HandlerFunc)
HandlerFunc registers a new resource by http.HandlerFunc
func (*AppRoute) Middlewares ¶
func (r *AppRoute) Middlewares() []Middleware
Middlewares returns registered middlewares of AppRoute
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) ProxyHandle ¶
func (r *AppRoute) ProxyHandle(method string, path string, proxy *httputil.ReverseProxy, filters ...ResponseFilter)
ProxyHandle registers a new resource with a proxy
func (*AppRoute) Resource ¶
Resource generates routes with controller interfaces, and returns a group routes with resource name.
Example:
article := r.Resource("article") GET /article Article.Index POST /article Article.Create HEAD /article/:article Article.Explore GET /article/:article Article.Show PUT /article/:article Article.Update DELETE /article/:article Article.Destroy
func (*AppRoute) ServeHTTP ¶
func (r *AppRoute) ServeHTTP(resp http.ResponseWriter, req *http.Request)
ServeHTTP implements http.Handler by proxy to wrapped Handler
func (*AppRoute) SetHandler ¶
SetHandler replaces hanlder of AppRoute
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 }
AppServer defines server component of gogo
func New ¶
New creates application server with config resolved from file <srcPath>/config/application[.<runMode>].json. NOTE: You can custom resolver by overwriting FindModeConfigFile.
func NewAppServer ¶
NewAppServer returns *AppServer inited with args
func NewDefaults ¶ added in v1.1.0
func NewDefaults() *AppServer
NewDefaults creates a *AppServer for quick start
func NewWithConfiger ¶
NewWithConfiger creates application server with custom Configer and default Logger, see Configer for implements a new config provider.
func NewWithLogger ¶
NewWithLogger creates application server with custom Configer and Logger
func (*AppServer) Run ¶
func (s *AppServer) Run()
Run starts the http server with httpdispatch.Router handler
func (*AppServer) RunWithHandler ¶
RunWithHandler runs the http server with given handler It's useful for embbedding third-party golang applications.
type Configer ¶
type Configer interface { RunMode() RunMode RunName() string SetMode(mode RunMode) Section() *SectionConfig UnmarshalJSON(v interface{}) error }
Configer represents application configurations
type Context ¶
type Context struct { Response Responser Request *http.Request Params *AppParams Logger Logger // contains filtered or unexported fields }
Context defines context of a request
func (*Context) Controller ¶
Controller returns controller name of routed handler
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 it doesn't exist
func (*Context) MustSetFinal ¶
MustSetFinal likes SetFinal, but it panics if key is duplicated.
func (*Context) Next ¶
func (c *Context) Next()
Next executes the remain middlewares in the chain. NOTE: It ONLY used in the middlewares!
func (*Context) RequestURI ¶
RequestURI returns request raw uri of http.Request
type ContextHandle ¶
type ContextHandle struct {
// contains filtered or unexported fields
}
ContextHandle wraps extra info for handler, such as package name, controller name and action name, etc.
func NewContextHandle ¶
func NewContextHandle(server *AppServer, handler http.HandlerFunc, filters []Middleware) *ContextHandle
NewContextHandle returns new *ContextHandle with handler info parsed
func (*ContextHandle) Handle ¶
func (ch *ContextHandle) Handle(w http.ResponseWriter, r *http.Request, params httpdispatch.Params)
Handle implements httpdispatch.Handler interface
type ControllerCreate ¶
type ControllerCreate interface {
Create(c *Context)
}
ControllerCreate is an interface that wraps the Create method. It is used by Resource for registering POST /resource route handler.
type ControllerDestroy ¶
type ControllerDestroy interface {
Destroy(c *Context)
}
ControllerDestroy is an interface that wraps the Destroy method. It is used by Resource for registering DELETE /resource/:id route handler.
type ControllerDispatch ¶
type ControllerDispatch interface {
DISPATCH(c *Context)
}
ControllerDispatch is an interface that allows custom router for Resource.
type ControllerExplore ¶
type ControllerExplore interface {
Explore(c *Context)
}
ControllerExplore is an interface that wraps the Explore method. It is used by Resource for registering HEAD /resource/:id route handler.
type ControllerID ¶
type ControllerID interface {
ID() string
}
ControllerID is an interface that allows custom resource id name with Resource.
type ControllerIndex ¶
type ControllerIndex interface {
Index(c *Context)
}
ControllerIndex is an interface that wraps the Index method. It is used by Resource for registering GET /resource route handler.
type ControllerShow ¶
type ControllerShow interface {
Show(c *Context)
}
ControllerShow is an interface that wraps the Show method. It is used by Resource for registering GET /resource/:id route handler.
type ControllerUpdate ¶
type ControllerUpdate interface {
Update(c *Context)
}
ControllerUpdate is an interface that wraps the Update method. It is used by Resource for registering PUT /resource/:id route handler.
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 FakeHandle ¶
type FakeHandle struct { *ContextHandle // contains filtered or unexported fields }
FakeHandle defines a wrapper of handler for testing
func NewFakeHandle ¶
func NewFakeHandle(server *AppServer, handler http.HandlerFunc, filters []Middleware, w http.ResponseWriter) *FakeHandle
NewFakeHandle returns new handler with stubbed http.ResponseWriter
func (*FakeHandle) Handle ¶
func (ch *FakeHandle) Handle(w http.ResponseWriter, r *http.Request, params httpdispatch.Params)
Handle implements httpdispatch.Handler interface
type GID ¶
type GID string
GID is a unique ID identifying a value. It must be exactly 12 bytes long.
func GIDHex ¶
GIDHex returns a GID from the provided hex representation. Calling this function with an invalid hex representation will cause a runtime panic. See the IsGIDHex function.
func NewGIDWithTime ¶
NewGIDWithTime returns a dummy GID with the timestamp part filled with the provided number of seconds from epoch UTC, and all other parts filled with zeroes. It is useful only for queries filter with ids generated before or after the specified timestamp.
func (GID) Counter ¶
Counter returns the incrementing value part of the id. It's a runtime error to call this method with an invalid id.
func (GID) Mac ¶
Mac returns the 3-byte mac addr id part of the id. It's a runtime error to call this method with an invalid id.
func (GID) Pid ¶
Pid returns the process id part of the id. It's a runtime error to call this method with an invalid id.
func (GID) String ¶
String returns a hex string representation of the id. Example: GIDHex("4d88e15b60f486e428412dc9").
type Handler ¶
type Handler interface { http.Handler Handle(string, string, httpdispatch.Handler) ServeFiles(string, http.FileSystem) }
Handler represents server handlers
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 Reuse(log 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] FilterFields []string `json:"filter_fields"` // sensitive fields which should filter out when logging }
LoggerConfig defines config spec of AppLogger
func (*LoggerConfig) Level ¶
func (l *LoggerConfig) Level() logger.Level
Level returns logger.Level by its name
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 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 }
Response extends http.ResponseWriter with extra metadata
func (*Response) Before ¶
func (r *Response) Before(filter ResponseFilter)
Before registers filters which invoked before response has written
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 true if response headers has written
func (*Response) Reset ¶
func (r *Response) Reset(w http.ResponseWriter)
Reset resets the current *Response with new http.ResponseWriter
func (*Response) Write ¶
Write writes data to client, and returns size of data written or error if exits.
func (*Response) WriteHeader ¶
WriteHeader sets response status code only by overwrites underline
type ResponseFilter ¶
ResponseFilter defines filter interface applied to response
type Responser ¶
type Responser interface { http.ResponseWriter http.Flusher Before(filter ResponseFilter) // 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 Reset(w http.ResponseWriter) // reset response with new http.ResponseWriter }
Responser represents HTTP response interface
func NewResponse ¶
func NewResponse(w http.ResponseWriter) Responser
NewResponse returns a Responser with w passed. NOTE: It sets default response status code to http.StatusOK
type RunMode ¶
type RunMode string
RunMode defines app run mode
const ( Development RunMode = "development" Test RunMode = "test" Production RunMode = "production" )
run mode
func (RunMode) IsDevelopment ¶
IsDevelopment returns true if mode is development
func (RunMode) IsProduction ¶
IsProduction returns true if mode equals to production
type SectionConfig ¶
type SectionConfig struct { Server *ServerConfig `json:"server"` Logger *LoggerConfig `json:"logger"` }
SectionConfig defines config spec for internal usage
type ServerConfig ¶
type ServerConfig struct { Addr string `json:"addr"` Port int `json:"port"` RTimeout int `json:"request_timeout"` // unit in second WTimeout int `json:"response_timeout"` // unit in second MaxHeaderBytes int `json:"max_header_bytes"` // unit in byte Ssl bool `json:"ssl"` SslCert string `json:"ssl_cert"` SslKey string `json:"ssl_key"` Throttle int `json:"throttle"` // in time.Second/throttle ms Slowdown int `json:"slowdown"` RequestID string `json:"request_id"` }
ServerConfig defines config spec of AppServer
type StatusCoder ¶
type StatusCoder interface {
StatusCode() int
}
StatusCoder represents HTTP response status code it is useful for custom response data with 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.