Documentation ¶
Index ¶
- Constants
- Variables
- func AbsoluteUrl(req *Request, path string) string
- func AddConfigParser(v interface{}, fun func(string) (interface{}, error))
- func AddViewHelper(name string, f interface{})
- func ConfigureProcess(filepath string) error
- func FormatDate(t time.Time) string
- func FormatDateTime(t time.Time) string
- func HandlerFunc(h http.Handler) func(*Response, *Request)
- func IsGuest(u User) bool
- func IsNil(v interface{}) bool
- func IsZero(v interface{}) bool
- func LoadConfig(cfg interface{}, section string) error
- func Must(t interface{}, err error) interface{}
- func ParseCookie(line string) *http.Cookie
- func ParseDate(str string) (time.Time, error)
- func ParseDateTime(str string) (time.Time, error)
- func ParseInt(str string, d, min, max int) int
- func RegisterProcessConfig(cfg interface{}, section string, onchange func(v interface{}))
- func RetryUntil(cond func() error, timeout time.Duration, interval time.Duration) error
- func SessionStoreTest(store SessionStore, t *testing.T)
- func ShallowCopy(dst, src interface{})
- func Shorten(str string, max int) string
- func Sign(value string, key string) string
- func UUID() (string, error)
- func Unsign(value string, key string) (string, error)
- func WaitLogs()
- type ApplicationError
- type Assert
- func (a *Assert) Debug(format string, param ...interface{})
- func (a *Assert) DebugData(data interface{})
- func (a *Assert) EqFloat32(expect, got float32, msg string, params ...interface{}) *Assert
- func (a *Assert) EqFloat64(expect, got float64, msg string, params ...interface{}) *Assert
- func (a *Assert) EqInt(expect, got int, msg string, params ...interface{}) *Assert
- func (a *Assert) EqInt32(expect, got int32, msg string, params ...interface{}) *Assert
- func (a *Assert) EqInt64(expect, got int64, msg string, params ...interface{}) *Assert
- func (a *Assert) EqStr(expect, got string, msg string, params ...interface{}) *Assert
- func (a *Assert) EqTime(expect, got time.Time, msg string, params ...interface{}) *Assert
- func (a *Assert) Error(format string, param ...interface{})
- func (a *Assert) ErrorData(data interface{})
- func (a *Assert) Fatal(format string, param ...interface{})
- func (a *Assert) FatalData(data interface{})
- func (a *Assert) GtInt(min, got int, msg string, params ...interface{}) *Assert
- func (a *Assert) Info(format string, param ...interface{})
- func (a *Assert) InfoData(data interface{})
- func (a *Assert) LtInt(max, got int, msg string, params ...interface{}) *Assert
- func (a *Assert) Nil(v interface{}, msg string, params ...interface{}) *Assert
- func (a *Assert) Not(ok bool, msg string, params ...interface{}) *Assert
- func (a *Assert) NotNil(v interface{}, msg string, params ...interface{}) *Assert
- func (a *Assert) NotZero(v interface{}, msg string, params ...interface{}) *Assert
- func (a *Assert) Ok(ok bool, msg string, params ...interface{}) *Assert
- func (a *Assert) Trace(format string, param ...interface{})
- func (a *Assert) TraceData(data interface{})
- func (a *Assert) Warn(format string, param ...interface{})
- func (a *Assert) WarnData(data interface{})
- func (a *Assert) Zero(v interface{}, msg string, params ...interface{}) *Assert
- type CompiledFormatter
- type ConfigFile
- type DataBag
- func (d DataBag) Decode(b []byte) error
- func (d DataBag) Delete(k string)
- func (d DataBag) Encode() ([]byte, error)
- func (d DataBag) Get(key string) (string, bool)
- func (d DataBag) GetBool(key string) (bool, bool)
- func (d DataBag) GetData(key string) (DataBag, bool)
- func (d DataBag) GetFloat(key string) (float64, bool)
- func (d DataBag) GetInt(key string) (int64, bool)
- func (d DataBag) GetTime(key string) (t time.Time, ok bool)
- func (d DataBag) Set(key string, val string)
- func (d DataBag) SetBool(key string, val bool)
- func (d DataBag) SetData(key string, val DataBag)
- func (d DataBag) SetFloat(key string, val float64)
- func (d DataBag) SetInt(key string, val int64)
- func (d DataBag) SetTime(key string, val time.Time)
- type LocalServer
- type LogLevel
- type LogRecord
- type LogRecordFormatter
- type LogSink
- type LogSinkManager
- type Logger
- type MemorySessionStore
- type Request
- func (r *Request) Cookie(key string) (*http.Cookie, error)
- func (r *Request) Form(key string) string
- func (r *Request) Header(key string) string
- func (r *Request) HttpRequest() *http.Request
- func (r *Request) IsTest() bool
- func (r *Request) Json(v interface{}) error
- func (r *Request) Local(key string) interface{}
- func (r *Request) Method() string
- func (r *Request) Param(key string) string
- func (r *Request) Proto() string
- func (r *Request) Query(key string) string
- func (r *Request) Referer() string
- func (r *Request) RemoteAddr() string
- func (r *Request) RemoteHost() string
- func (r *Request) SetLocal(key string, val interface{})
- func (r *Request) SignedCookie(name string, keys ...string) (*http.Cookie, error)
- func (r *Request) URL() *url.URL
- func (r *Request) UserAgent() string
- func (r *Request) Version() string
- type Response
- func (res *Response) Close()
- func (res *Response) End()
- func (res *Response) Flush() error
- func (res *Response) Header() http.Header
- func (res *Response) IsClosed() bool
- func (r *Response) Local(key string) interface{}
- func (res *Response) Redirect(urlStr string, code int)
- func (res *Response) RenderError(err ApplicationError)
- func (res *Response) RenderInternalError(msg string, v ...interface{})
- func (res *Response) ResponseTime() time.Duration
- func (res *Response) SetCookie(c *http.Cookie)
- func (r *Response) SetLocal(key string, val interface{})
- func (r *Response) SetSignedCookie(c *http.Cookie, key string)
- func (res *Response) Templates(paths ...string) error
- func (res *Response) TemplatesWithStatus(st int, headers map[string]string, paths ...string) error
- func (res *Response) Write(b []byte) (int, error)
- func (res *Response) WriteHeader(status int)
- func (res *Response) WriteJson(v interface{}) error
- func (res *Response) WriteJsonWithStatus(st int, headers map[string]string, v interface{}) error
- func (res *Response) WriteString(str string, v ...interface{}) error
- func (res *Response) WrittenBytes() int64
- type Route
- type Router
- func (r *Router) After(handler func(rse *Response, req *Request))
- func (r *Router) All(pattern string, handler ...func(res *Response, req *Request))
- func (r *Router) Before(handler func(rse *Response, req *Request))
- func (r *Router) Delete(pattern string, handler ...func(res *Response, req *Request))
- func (r *Router) Dispatch(res *Response, req *Request) []*Route
- func (r *Router) Get(pattern string, handler ...func(res *Response, req *Request))
- func (r *Router) Mount(r1 *Router)
- func (r *Router) NotFound(handler func(rse *Response, req *Request))
- func (r *Router) Post(pattern string, handler ...func(res *Response, req *Request))
- func (r *Router) Put(pattern string, handler ...func(res *Response, req *Request))
- func (r *Router) String() string
- type Server
- type Session
- type SessionStore
- type User
- type View
Constants ¶
const ( METHOD_GET = "GET" METHOD_PUT = "PUT" METHOD_POST = "POST" METHOD_DELETE = "DELETE" METHOD_ALL = "ALL" // matching with all methods )
const FormDateFormat = "2006-01-02"
const FormDateTimeFormat = "2006-01-02 15:04:05 MST"
const FormTimeFormat = "15:04"
const FormTimeSFormat = "15:04:05"
const ISO8601 = "2006-01-02T15:04:05Z"
const ISO8601_DATE = "2006-01-02"
const ParseIntMax = math.MaxInt32
const ParseIntMin = math.MinInt32
Variables ¶
var ErrSignatureModified = errors.New("http: signed value was modified")
var ErrWrongSignatureFormat = errors.New("http: wrong signature format")
var GuestUser = &guestUser{}
var LogConfig = &logConfig{}
Log Configuration in the process.
var LogLevelDebug = &LogLevel{Level: 1, Str: "DEBUG"}
var LogLevelError = &LogLevel{Level: 4, Str: "ERROR"}
var LogLevelFatal = &LogLevel{Level: 5, Str: "FATAL"}
var LogLevelInfo = &LogLevel{Level: 2, Str: "INFO"}
var LogLevelTrace = &LogLevel{Level: 0, Str: "TRACE"}
var LogLevelWarn = &LogLevel{Level: 3, Str: "WARN"}
var ServerConfig = &serverConfig{}
var ViewConfig = &viewConfig{ BaseDir: "templates", RenderInternalError: true, CacheTemplate: true, templateCache: make(map[string]*template.Template), }
var ViewHelpers = template.FuncMap{ "date": func(t time.Time) string { return t.In(ViewTimezone).Format(FormDateFormat) }, "datetime": func(t time.Time) string { return t.In(ViewTimezone).Format(FormDateTimeFormat) }, "time": func(t time.Time) string { return t.In(ViewTimezone).Format(FormTimeFormat) }, "times": func(t time.Time) string { return t.In(ViewTimezone).Format(FormTimeSFormat) }, "loop": func(from, to int) []int { if to-from <= 0 { return []int{} } iter := make([]int, to-from) for i, _ := range iter { iter[i] = i + from } return iter }, "bytes2string": func(b []byte) string { return string(b) }, "safe_html": func(s string) template.HTML { return template.HTML(s) }, "dump": func(l map[string]interface{}) string { var buff bytes.Buffer for k, v := range l { buff.Write([]byte(fmt.Sprintf("%s: %v\n", k, v))) } return buff.String() }, }
var ViewTimezone = time.UTC
Functions ¶
func AbsoluteUrl ¶
func AddConfigParser ¶
Add a configuration parser for the type of v.
func AddViewHelper ¶
func AddViewHelper(name string, f interface{})
func ConfigureProcess ¶
Configuring process with file path.
func FormatDateTime ¶
Use ISO8601 format: 2006-01-02T15:04:05Z
func HandlerFunc ¶
Convert normal Handler to wcg's handler function.
func IsNil ¶
func IsNil(v interface{}) bool
Return true if v is a nil value. Use this for interface{} object http://golang.org/doc/faq#nil_error
func IsZero ¶
func IsZero(v interface{}) bool
Return true if v is a zero value. See https://code.google.com/p/go/issues/detail?id=7501
func LoadConfig ¶
func ParseCookie ¶
Parse the cookie line and return a cookie object.
func ParseDateTime ¶
Use ISO8601 format: 2006-01-02T15:04:05Z
func RegisterProcessConfig ¶
func RegisterProcessConfig(cfg interface{}, section string, onchange func(v interface{}))
Register object updated when process configuration file is changed or reloaded.
func RetryUntil ¶
func SessionStoreTest ¶
func SessionStoreTest(store SessionStore, t *testing.T)
Perform a generic test for SessionStore implementation
func ShallowCopy ¶
func ShallowCopy(dst, src interface{})
Shallow Copy from src to dst. Both of which should be an pointer value, otherwise this raise a panic.
func UUID ¶
Random UUID following RFC4122 Section 4.4 https://www.ietf.org/rfc/rfc4122.txt
Types ¶
type ApplicationError ¶
type ApplicationError interface {
StatusCode() int
}
type Assert ¶
type Assert struct {
// contains filtered or unexported fields
}
type CompiledFormatter ¶
type CompiledFormatter struct {
// contains filtered or unexported fields
}
func NewCompiledFormatter ¶
func NewCompiledFormatter(f string, repl func(string, ...interface{}) []byte) *CompiledFormatter
Create a new CompiledFormatter object from a format string and evaluators.
- f - a string format
- fun - a function that receive a variable name [*1] and context values, and return []byte to replace the variable.
This is similar to Regexp.ReplaceAllFunc(src []byte, repl func([]byte)[]byte) but CompiledFormatter can be faster than ReplaceAllFunc [*2] since it compiles format src into function list and applied context values many times.
[*1] variable name is a represented char sequence as $[a-zA-Z0-9:-]+ in f (case insensitive). [*2] You can see how fast CompiledFormatter is by using benchmarks
Example:
const format = "Test $var1 $var2" repl := func(varname string, v...interface) []byte { replace, ok := v[0][varname] if ok { return replace }else { return []byte(varname) } } formatter := NewCompiledFormatter(format, repl) varmap := map[string]([]byte) { "$VAR1" : []byte("foo") } formatter.Format(varmap) // => []byte("Test foo $var2")
func (CompiledFormatter) Format ¶
func (c CompiledFormatter) Format(v ...interface{}) []byte
Evaluate the compiled string and return the result as []byte
func (CompiledFormatter) FormatTo ¶
func (c CompiledFormatter) FormatTo(w io.Writer, v ...interface{})
Evaluate the compiled string and write the result into w.
type ConfigFile ¶
type ConfigFile struct {
// contains filtered or unexported fields
}
func NewConfig ¶
func NewConfig(str string) (*ConfigFile, error)
func NewConfigFile ¶
func NewConfigFile(filename string) (*ConfigFile, error)
func (*ConfigFile) Load ¶
func (c *ConfigFile) Load(cfg interface{}, section string) (err error)
type DataBag ¶
type DataBag map[string]interface{}
DataBag is an alias for map[string]interface{} for user defined data set and provides some utilities to access the data.
The supported value type of DataBag supports string, int64, float64, time.Time, bool and DataBag itself.
DataBag can be serializable to JSON without any additional efforts by user even though some of data types are not supported in JSON.
Support accessors are GetXXXX(key string). Getter returns typed value and bool which implies the data exists or not. If the same key exists with different types (and inconversion to original) it would be false.
type LocalServer ¶
type LocalServer struct { Addr string // contains filtered or unexported fields }
LocalServer is a Server implementation using http.Server.
func NewLocalServer ¶
func NewLocalServer() *LocalServer
func (*LocalServer) Routes ¶
func (s *LocalServer) Routes() *Router
func (*LocalServer) Run ¶
func (s *LocalServer) Run() error
func (*LocalServer) Stop ¶
func (s *LocalServer) Stop(graceful bool) error
Stop the server. TODO: When `graceful` is true, this would wait for all incoming requests being completed.
type LogRecord ¶
type LogRecord struct { Level *LogLevel `json:"level"` Timestamp time.Time `json:"timestamp"` SourceFile string `json:"source_file"` SourceLine int `json:"source_line"` SourceStack []string `json:"source_stack"` Goroutine int `json:"goroutine"` RequestId string `json:"request_id,omitempty"` SessionId string `json:"session_id,omitempty"` UserId string `json:"user_id,omitempty"` Data interface{} `json:"data,omitempty"` Text string `json:"text,omitempty"` Request *Request }
type LogRecordFormatter ¶
type LogRecordFormatter struct {
*CompiledFormatter
}
func NewLogRecordFormatter ¶
func NewLogRecordFormatter(format string) *LogRecordFormatter
type LogSinkManager ¶
type LogSinkManager struct {
// contains filtered or unexported fields
}
LogSinkManager is an struct that manage concurrency for forwarding logs to LogSink.
func NewLogSinkManager ¶
func NewLogSinkManager(l *LogLevel, s LogSink, chSize int) *LogSinkManager
func (*LogSinkManager) Forward ¶
func (lsm *LogSinkManager) Forward(r *LogRecord)
Forward logs to a goroutine that write logs to sink via channel. the log records forwarded after Stop() would be lost
type Logger ¶
type Logger interface { Trace(string, ...interface{}) TraceData(interface{}) Debug(string, ...interface{}) DebugData(interface{}) Info(string, ...interface{}) InfoData(interface{}) Warn(string, ...interface{}) WarnData(interface{}) Error(string, ...interface{}) ErrorData(interface{}) Fatal(string, ...interface{}) FatalData(interface{}) }
type MemorySessionStore ¶
type MemorySessionStore struct {
// contains filtered or unexported fields
}
func NewMemorySessionStore ¶
func NewMemorySessionStore() *MemorySessionStore
func (*MemorySessionStore) Save ¶
func (ms *MemorySessionStore) Save(sess *Session) error
type Request ¶
type Request struct { RequestId string Session *Session Logger Logger User User // contains filtered or unexported fields }
func NewRequest ¶
func NewTestRequest ¶
func (*Request) HttpRequest ¶
Returns an *http.Request bound with the object
func (*Request) Json ¶
Parse request body JSON and unmarshal it into v. If this function is called once, the request object would cache the parsed result and return shallow-copy of it when it is called twice or more. so the type of v should be consistent in a request, otherwise this would cause a panic.
foo := new(Foo) req.Json(foo) // parse request body and unmarshal on foo.
// in another handler of the same request. foo1 := new(Foo) req.Json(foo1) // copy foo to foo1.
// in another handler of the same request. bar := new(Bar) req.Json(bar) // this would raise a panic!!
func (*Request) SignedCookie ¶
Get a sha256-signed cookie. It would be helpful if you want to ensure the cookie sent by clients are not modified. The key can be listed on the last arguments, so that if you want to change the key during migration window, you can use like `SignedCookie(name, newkey, oldkey)` to decode the cookie with one of keys.
type Response ¶
type Response struct { Request *Request StatusCode int StartTime time.Time EndTime time.Time // contains filtered or unexported fields }
A wrapper struct of http.ResponseWriter
func NewResponse ¶
func NewResponse(writer http.ResponseWriter, req *Request) *Response
Create a new Response object from http.ResponseWriter
func (*Response) Close ¶
func (res *Response) Close()
Close the current http transaction not to send any more contents to the client.
func (*Response) RenderError ¶
func (res *Response) RenderError(err ApplicationError)
func (*Response) RenderInternalError ¶
func (*Response) ResponseTime ¶
Returns a time taken for the response.
func (*Response) SetSignedCookie ¶
Set Cookie with a sha256 sign. It would be helpful if you want to ensure the cookie sent by clients are not modified.
func (*Response) Templates ¶
Response generated by templates. template paths should be alternate paths from AppConfig["ViewDir"].
func (*Response) TemplatesWithStatus ¶
Response generated by templates with a http status line and headers. `headers` can be nil, which means no additional headers.
func (*Response) WriteHeader ¶
Write a status line and headers.
func (*Response) WriteJsonWithStatus ¶
Response a json string with a http status line and headers. `headers` can be nil, which means no additional headers.
func (*Response) WriteString ¶
func (*Response) WrittenBytes ¶
Returns a written bytes of body
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Each route object managed in Router.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router manages routing tables and dispatch the HTTP requests.
func (*Router) After ¶
Add an middleware after processing each request handler. Registered middleware are processed even after the response gets closed.
func (*Router) All ¶
Add a route to handler that would be mached with all HTTP methods with the specified pattern.
func (*Router) Before ¶
Add an middleware before processing each request handler. Registered middleware are processed even after the response gets closed.
func (*Router) Delete ¶
Add a route to handler that would be mached with DELETE methods with the specified pattern.
func (*Router) Dispatch ¶
Dispatch a pair of request and response and returns the array of matched routes. If no routes are matched, this returns nil.
func (*Router) Get ¶
Add a route to handler that would be mached with GET methods with the specified pattern.
func (*Router) Post ¶
Add a route to handler that would be mached with POST methods with the specified pattern.
type Session ¶
type Session struct { Id string `json:"id"` // Session ID Timestamp time.Time `json:"timestamp"` // timestamp when session is stored. DataBag `json:"data"` // User Data, should be used via Get/Set methods. CSRFSecret string `json:"csrf_secret"` // sign secret for csrf token }
func (*Session) ValidateToken ¶
type SessionStore ¶
type SessionStore interface { // Load a session from storage. If not found, it should return nil without errror. Load(id string) (*Session, error) // Save a session on storage. // error should be returned when access path to storage is lost. Save(sess *Session) error // Delete a session from storage. If the id exists and deleted, return true, otherwise false. // error should be returned when access path to storage is lost. Delete(id string) (bool, error) }
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
examples
|
|
test
This package provides test utilities for 'goapp test' DO NOT import this package in the deployment app.
|
This package provides test utilities for 'goapp test' DO NOT import this package in the deployment app. |
github
github package provides an API client for github.com Copyright (C) 2014 Yohei Sasaki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
|
github package provides an API client for github.com Copyright (C) 2014 Yohei Sasaki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. |
Validation utility Copyright (C) 2014 Yohei Sasaki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
|
Validation utility Copyright (C) 2014 Yohei Sasaki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. |