mirror of
https://github.com/astaxie/beego.git
synced 2024-11-22 02:20:54 +00:00
More minor grammar fixes
This commit is contained in:
parent
2fce8f9d1b
commit
1b4bb43df0
22
pkg/cache/cache.go
vendored
22
pkg/cache/cache.go
vendored
@ -47,23 +47,23 @@ import (
|
|||||||
// c.Incr("counter") // now is 2
|
// c.Incr("counter") // now is 2
|
||||||
// count := c.Get("counter").(int)
|
// count := c.Get("counter").(int)
|
||||||
type Cache interface {
|
type Cache interface {
|
||||||
// get cached value by key.
|
// Get a cached value by key.
|
||||||
Get(key string) interface{}
|
Get(key string) interface{}
|
||||||
// GetMulti is a batch version of Get.
|
// GetMulti is a batch version of Get.
|
||||||
GetMulti(keys []string) []interface{}
|
GetMulti(keys []string) []interface{}
|
||||||
// set cached value with key and expire time.
|
// Set a cached value with key and expire time.
|
||||||
Put(key string, val interface{}, timeout time.Duration) error
|
Put(key string, val interface{}, timeout time.Duration) error
|
||||||
// delete cached value by key.
|
// Delete cached value by key.
|
||||||
Delete(key string) error
|
Delete(key string) error
|
||||||
// increase cached int value by key, as a counter.
|
// Increment a cached int value by key, as a counter.
|
||||||
Incr(key string) error
|
Incr(key string) error
|
||||||
// decrease cached int value by key, as a counter.
|
// Decrement a cached int value by key, as a counter.
|
||||||
Decr(key string) error
|
Decr(key string) error
|
||||||
// check if cached value exists or not.
|
// Check if a cached value exists or not.
|
||||||
IsExist(key string) bool
|
IsExist(key string) bool
|
||||||
// clear all cache.
|
// Clear all cache.
|
||||||
ClearAll() error
|
ClearAll() error
|
||||||
// start gc routine based on config string settings.
|
// Start gc routine based on config string settings.
|
||||||
StartAndGC(config string) error
|
StartAndGC(config string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,9 +85,9 @@ func Register(name string, adapter Instance) {
|
|||||||
adapters[name] = adapter
|
adapters[name] = adapter
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCache Create a new cache driver by adapter name and config string.
|
// NewCache creates a new cache driver by adapter name and config string.
|
||||||
// config need to be correct JSON as string: {"interval":360}.
|
// config: must be in JSON format such as {"interval":360}.
|
||||||
// it will start gc automatically.
|
// Starts gc automatically.
|
||||||
func NewCache(adapterName, config string) (adapter Cache, err error) {
|
func NewCache(adapterName, config string) (adapter Cache, err error) {
|
||||||
instanceFunc, ok := adapters[adapterName]
|
instanceFunc, ok := adapters[adapterName]
|
||||||
if !ok {
|
if !ok {
|
||||||
|
2
pkg/cache/file.go
vendored
2
pkg/cache/file.go
vendored
@ -54,7 +54,7 @@ type FileCache struct {
|
|||||||
EmbedExpiry int
|
EmbedExpiry int
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFileCache cerates a new file cache with no config.
|
// NewFileCache creates a new file cache with no config.
|
||||||
// The level and expiry need to be set in the method StartAndGC as config string.
|
// The level and expiry need to be set in the method StartAndGC as config string.
|
||||||
func NewFileCache() Cache {
|
func NewFileCache() Cache {
|
||||||
// return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix}
|
// return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix}
|
||||||
|
22
pkg/cache/memcache/memcache.go
vendored
22
pkg/cache/memcache/memcache.go
vendored
@ -46,7 +46,7 @@ type Cache struct {
|
|||||||
conninfo []string
|
conninfo []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMemCache create new memcache adapter.
|
// NewMemCache creates a new memcache adapter.
|
||||||
func NewMemCache() cache.Cache {
|
func NewMemCache() cache.Cache {
|
||||||
return &Cache{}
|
return &Cache{}
|
||||||
}
|
}
|
||||||
@ -64,7 +64,7 @@ func (rc *Cache) Get(key string) interface{} {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMulti get value from memcache.
|
// GetMulti gets a value from a key in memcache.
|
||||||
func (rc *Cache) GetMulti(keys []string) []interface{} {
|
func (rc *Cache) GetMulti(keys []string) []interface{} {
|
||||||
size := len(keys)
|
size := len(keys)
|
||||||
var rv []interface{}
|
var rv []interface{}
|
||||||
@ -89,7 +89,7 @@ func (rc *Cache) GetMulti(keys []string) []interface{} {
|
|||||||
return rv
|
return rv
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put put value to memcache.
|
// Put puts a value into memcache.
|
||||||
func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error {
|
func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -107,7 +107,7 @@ func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error {
|
|||||||
return rc.conn.Set(&item)
|
return rc.conn.Set(&item)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete delete value in memcache.
|
// Delete deletes a value in memcache.
|
||||||
func (rc *Cache) Delete(key string) error {
|
func (rc *Cache) Delete(key string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -117,7 +117,7 @@ func (rc *Cache) Delete(key string) error {
|
|||||||
return rc.conn.Delete(key)
|
return rc.conn.Delete(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Incr increase counter.
|
// Incr increases counter.
|
||||||
func (rc *Cache) Incr(key string) error {
|
func (rc *Cache) Incr(key string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -128,7 +128,7 @@ func (rc *Cache) Incr(key string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decr decrease counter.
|
// Decr decreases counter.
|
||||||
func (rc *Cache) Decr(key string) error {
|
func (rc *Cache) Decr(key string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -139,7 +139,7 @@ func (rc *Cache) Decr(key string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsExist check value exists in memcache.
|
// IsExist checks if a value exists in memcache.
|
||||||
func (rc *Cache) IsExist(key string) bool {
|
func (rc *Cache) IsExist(key string) bool {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -150,7 +150,7 @@ func (rc *Cache) IsExist(key string) bool {
|
|||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll clear all cached in memcache.
|
// ClearAll clears all cache in memcache.
|
||||||
func (rc *Cache) ClearAll() error {
|
func (rc *Cache) ClearAll() error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -160,9 +160,9 @@ func (rc *Cache) ClearAll() error {
|
|||||||
return rc.conn.FlushAll()
|
return rc.conn.FlushAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartAndGC start memcache adapter.
|
// StartAndGC starts the memcache adapter.
|
||||||
// config string is like {"conn":"connection info"}.
|
// config: must be in the format {"conn":"connection info"}.
|
||||||
// if connecting error, return.
|
// If an error occurs during connecting, an error is returned
|
||||||
func (rc *Cache) StartAndGC(config string) error {
|
func (rc *Cache) StartAndGC(config string) error {
|
||||||
var cf map[string]string
|
var cf map[string]string
|
||||||
json.Unmarshal([]byte(config), &cf)
|
json.Unmarshal([]byte(config), &cf)
|
||||||
|
31
pkg/cache/redis/redis.go
vendored
31
pkg/cache/redis/redis.go
vendored
@ -43,7 +43,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// DefaultKey the collection name of redis for cache adapter.
|
// The collection name of redis for the cache adapter.
|
||||||
DefaultKey = "beecacheRedis"
|
DefaultKey = "beecacheRedis"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -56,16 +56,16 @@ type Cache struct {
|
|||||||
password string
|
password string
|
||||||
maxIdle int
|
maxIdle int
|
||||||
|
|
||||||
// the timeout to a value less than the redis server's timeout.
|
// Timeout value (less than the redis server's timeout value)
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewRedisCache create new redis cache with default collection name.
|
// NewRedisCache creates a new redis cache with default collection name.
|
||||||
func NewRedisCache() cache.Cache {
|
func NewRedisCache() cache.Cache {
|
||||||
return &Cache{key: DefaultKey}
|
return &Cache{key: DefaultKey}
|
||||||
}
|
}
|
||||||
|
|
||||||
// actually do the redis cmds, args[0] must be the key name.
|
// Execute the redis commands. args[0] must be the key name
|
||||||
func (rc *Cache) do(commandName string, args ...interface{}) (reply interface{}, err error) {
|
func (rc *Cache) do(commandName string, args ...interface{}) (reply interface{}, err error) {
|
||||||
if len(args) < 1 {
|
if len(args) < 1 {
|
||||||
return nil, errors.New("missing required arguments")
|
return nil, errors.New("missing required arguments")
|
||||||
@ -90,7 +90,7 @@ func (rc *Cache) Get(key string) interface{} {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMulti get cache from redis.
|
// GetMulti gets cache from redis.
|
||||||
func (rc *Cache) GetMulti(keys []string) []interface{} {
|
func (rc *Cache) GetMulti(keys []string) []interface{} {
|
||||||
c := rc.p.Get()
|
c := rc.p.Get()
|
||||||
defer c.Close()
|
defer c.Close()
|
||||||
@ -105,19 +105,19 @@ func (rc *Cache) GetMulti(keys []string) []interface{} {
|
|||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put put cache to redis.
|
// Put puts cache into redis.
|
||||||
func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error {
|
func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error {
|
||||||
_, err := rc.do("SETEX", key, int64(timeout/time.Second), val)
|
_, err := rc.do("SETEX", key, int64(timeout/time.Second), val)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete delete cache in redis.
|
// Delete deletes a key's cache in redis.
|
||||||
func (rc *Cache) Delete(key string) error {
|
func (rc *Cache) Delete(key string) error {
|
||||||
_, err := rc.do("DEL", key)
|
_, err := rc.do("DEL", key)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsExist check cache's existence in redis.
|
// IsExist checks cache's existence in redis.
|
||||||
func (rc *Cache) IsExist(key string) bool {
|
func (rc *Cache) IsExist(key string) bool {
|
||||||
v, err := redis.Bool(rc.do("EXISTS", key))
|
v, err := redis.Bool(rc.do("EXISTS", key))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -126,19 +126,19 @@ func (rc *Cache) IsExist(key string) bool {
|
|||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
// Incr increase counter in redis.
|
// Incr increases a key's counter in redis.
|
||||||
func (rc *Cache) Incr(key string) error {
|
func (rc *Cache) Incr(key string) error {
|
||||||
_, err := redis.Bool(rc.do("INCRBY", key, 1))
|
_, err := redis.Bool(rc.do("INCRBY", key, 1))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decr decrease counter in redis.
|
// Decr decreases a key's counter in redis.
|
||||||
func (rc *Cache) Decr(key string) error {
|
func (rc *Cache) Decr(key string) error {
|
||||||
_, err := redis.Bool(rc.do("INCRBY", key, -1))
|
_, err := redis.Bool(rc.do("INCRBY", key, -1))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll clean all cache in redis. delete this redis collection.
|
// ClearAll deletes all cache in the redis collection
|
||||||
func (rc *Cache) ClearAll() error {
|
func (rc *Cache) ClearAll() error {
|
||||||
cachedKeys, err := rc.Scan(rc.key + ":*")
|
cachedKeys, err := rc.Scan(rc.key + ":*")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -154,7 +154,7 @@ func (rc *Cache) ClearAll() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scan scan all keys matching the pattern. a better choice than `keys`
|
// Scan scans all keys matching a given pattern.
|
||||||
func (rc *Cache) Scan(pattern string) (keys []string, err error) {
|
func (rc *Cache) Scan(pattern string) (keys []string, err error) {
|
||||||
c := rc.p.Get()
|
c := rc.p.Get()
|
||||||
defer c.Close()
|
defer c.Close()
|
||||||
@ -183,10 +183,9 @@ func (rc *Cache) Scan(pattern string) (keys []string, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartAndGC start redis cache adapter.
|
// StartAndGC starts the redis cache adapter.
|
||||||
// config is like {"key":"collection key","conn":"connection info","dbNum":"0"}
|
// config: must be in this format {"key":"collection key","conn":"connection info","dbNum":"0"}
|
||||||
// the cache item in redis are stored forever,
|
// Cached items in redis are stored forever, no garbage collection happens
|
||||||
// so no gc operation.
|
|
||||||
func (rc *Cache) StartAndGC(config string) error {
|
func (rc *Cache) StartAndGC(config string) error {
|
||||||
var cf map[string]string
|
var cf map[string]string
|
||||||
json.Unmarshal([]byte(config), &cf)
|
json.Unmarshal([]byte(config), &cf)
|
||||||
|
27
pkg/cache/ssdb/ssdb.go
vendored
27
pkg/cache/ssdb/ssdb.go
vendored
@ -18,12 +18,12 @@ type Cache struct {
|
|||||||
conninfo []string
|
conninfo []string
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewSsdbCache create new ssdb adapter.
|
//NewSsdbCache creates new ssdb adapter.
|
||||||
func NewSsdbCache() cache.Cache {
|
func NewSsdbCache() cache.Cache {
|
||||||
return &Cache{}
|
return &Cache{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get get value from memcache.
|
// Get gets a key's value from memcache.
|
||||||
func (rc *Cache) Get(key string) interface{} {
|
func (rc *Cache) Get(key string) interface{} {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -37,7 +37,7 @@ func (rc *Cache) Get(key string) interface{} {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMulti get value from memcache.
|
// GetMulti gets one or keys values from memcache.
|
||||||
func (rc *Cache) GetMulti(keys []string) []interface{} {
|
func (rc *Cache) GetMulti(keys []string) []interface{} {
|
||||||
size := len(keys)
|
size := len(keys)
|
||||||
var values []interface{}
|
var values []interface{}
|
||||||
@ -63,7 +63,7 @@ func (rc *Cache) GetMulti(keys []string) []interface{} {
|
|||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
// DelMulti get value from memcache.
|
// DelMulti deletes one or more keys from memcache
|
||||||
func (rc *Cache) DelMulti(keys []string) error {
|
func (rc *Cache) DelMulti(keys []string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -74,7 +74,8 @@ func (rc *Cache) DelMulti(keys []string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put put value to memcache. only support string.
|
// Put puts value into memcache.
|
||||||
|
// value: must be of type string
|
||||||
func (rc *Cache) Put(key string, value interface{}, timeout time.Duration) error {
|
func (rc *Cache) Put(key string, value interface{}, timeout time.Duration) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -102,7 +103,7 @@ func (rc *Cache) Put(key string, value interface{}, timeout time.Duration) error
|
|||||||
return errors.New("bad response")
|
return errors.New("bad response")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete delete value in memcache.
|
// Delete deletes a value in memcache.
|
||||||
func (rc *Cache) Delete(key string) error {
|
func (rc *Cache) Delete(key string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -113,7 +114,7 @@ func (rc *Cache) Delete(key string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Incr increase counter.
|
// Incr increases a key's counter.
|
||||||
func (rc *Cache) Incr(key string) error {
|
func (rc *Cache) Incr(key string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -124,7 +125,7 @@ func (rc *Cache) Incr(key string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decr decrease counter.
|
// Decr decrements a key's counter.
|
||||||
func (rc *Cache) Decr(key string) error {
|
func (rc *Cache) Decr(key string) error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -135,7 +136,7 @@ func (rc *Cache) Decr(key string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsExist check value exists in memcache.
|
// IsExist checks if a key exists in memcache.
|
||||||
func (rc *Cache) IsExist(key string) bool {
|
func (rc *Cache) IsExist(key string) bool {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -153,7 +154,7 @@ func (rc *Cache) IsExist(key string) bool {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll clear all cached in memcache.
|
// ClearAll clears all cached items in memcache.
|
||||||
func (rc *Cache) ClearAll() error {
|
func (rc *Cache) ClearAll() error {
|
||||||
if rc.conn == nil {
|
if rc.conn == nil {
|
||||||
if err := rc.connectInit(); err != nil {
|
if err := rc.connectInit(); err != nil {
|
||||||
@ -195,9 +196,9 @@ func (rc *Cache) Scan(keyStart string, keyEnd string, limit int) ([]string, erro
|
|||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartAndGC start memcache adapter.
|
// StartAndGC starts the memcache adapter.
|
||||||
// config string is like {"conn":"connection info"}.
|
// config: must be in the format {"conn":"connection info"}.
|
||||||
// if connecting error, return.
|
// If an error occurs during connection, an error is returned
|
||||||
func (rc *Cache) StartAndGC(config string) error {
|
func (rc *Cache) StartAndGC(config string) error {
|
||||||
var cf map[string]string
|
var cf map[string]string
|
||||||
json.Unmarshal([]byte(config), &cf)
|
json.Unmarshal([]byte(config), &cf)
|
||||||
|
@ -224,7 +224,7 @@ func (ini *IniConfig) ParseData(data []byte) (config.Configer, error) {
|
|||||||
return ini.parseData(dir, data)
|
return ini.parseData(dir, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// IniConfigContainer A Config represents the ini configuration.
|
// IniConfigContainer is a config which represents the ini configuration.
|
||||||
// When set and get value, support key as section:name type.
|
// When set and get value, support key as section:name type.
|
||||||
type IniConfigContainer struct {
|
type IniConfigContainer struct {
|
||||||
data map[string]map[string]string // section=> key:val
|
data map[string]map[string]string // section=> key:val
|
||||||
|
@ -66,7 +66,7 @@ func (js *JSONConfig) ParseData(data []byte) (config.Configer, error) {
|
|||||||
return x, nil
|
return x, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// JSONConfigContainer A Config represents the json configuration.
|
// JSONConfigContainer is a config which represents the json configuration.
|
||||||
// Only when get value, support key as section:name type.
|
// Only when get value, support key as section:name type.
|
||||||
type JSONConfigContainer struct {
|
type JSONConfigContainer struct {
|
||||||
data map[string]interface{}
|
data map[string]interface{}
|
||||||
|
@ -72,7 +72,7 @@ func (xc *Config) ParseData(data []byte) (config.Configer, error) {
|
|||||||
return x, nil
|
return x, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConfigContainer A Config represents the xml configuration.
|
// ConfigContainer is a Config which represents the xml configuration.
|
||||||
type ConfigContainer struct {
|
type ConfigContainer struct {
|
||||||
data map[string]interface{}
|
data map[string]interface{}
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
|
@ -116,7 +116,7 @@ func parseYML(buf []byte) (cnf map[string]interface{}, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConfigContainer A Config represents the yaml configuration.
|
// ConfigContainer is a config which represents the yaml configuration.
|
||||||
type ConfigContainer struct {
|
type ConfigContainer struct {
|
||||||
data map[string]interface{}
|
data map[string]interface{}
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
|
@ -32,14 +32,14 @@ var (
|
|||||||
defaultGzipMinLength = 20
|
defaultGzipMinLength = 20
|
||||||
// Content will only be compressed if content length is either unknown or greater than gzipMinLength.
|
// Content will only be compressed if content length is either unknown or greater than gzipMinLength.
|
||||||
gzipMinLength = defaultGzipMinLength
|
gzipMinLength = defaultGzipMinLength
|
||||||
//The compression level used for deflate compression. (0-9).
|
// Compression level used for deflate compression. (0-9).
|
||||||
gzipCompressLevel int
|
gzipCompressLevel int
|
||||||
// List of HTTP methods to compress. If not set, only GET requests are compressed.
|
// List of HTTP methods to compress. If not set, only GET requests are compressed.
|
||||||
includedMethods map[string]bool
|
includedMethods map[string]bool
|
||||||
getMethodOnly bool
|
getMethodOnly bool
|
||||||
)
|
)
|
||||||
|
|
||||||
// InitGzip init the gzipcompress
|
// InitGzip initializes the gzipcompress
|
||||||
func InitGzip(minLength, compressLevel int, methods []string) {
|
func InitGzip(minLength, compressLevel int, methods []string) {
|
||||||
if minLength >= 0 {
|
if minLength >= 0 {
|
||||||
gzipMinLength = minLength
|
gzipMinLength = minLength
|
||||||
@ -119,7 +119,7 @@ var (
|
|||||||
bestCompressionPool: &sync.Pool{New: func() interface{} { wr, _ := gzip.NewWriterLevel(nil, flate.BestCompression); return wr }},
|
bestCompressionPool: &sync.Pool{New: func() interface{} { wr, _ := gzip.NewWriterLevel(nil, flate.BestCompression); return wr }},
|
||||||
}
|
}
|
||||||
|
|
||||||
//according to the sec :http://tools.ietf.org/html/rfc2616#section-3.5 ,the deflate compress in http is zlib indeed
|
// According to: http://tools.ietf.org/html/rfc2616#section-3.5 the deflate compress in http is zlib indeed
|
||||||
// deflate
|
// deflate
|
||||||
// The "zlib" format defined in RFC 1950 [31] in combination with
|
// The "zlib" format defined in RFC 1950 [31] in combination with
|
||||||
// the "deflate" compression mechanism described in RFC 1951 [29].
|
// the "deflate" compression mechanism described in RFC 1951 [29].
|
||||||
@ -154,8 +154,8 @@ func WriteBody(encoding string, writer io.Writer, content []byte) (bool, string,
|
|||||||
return writeLevel(encoding, writer, bytes.NewReader(content), gzipCompressLevel)
|
return writeLevel(encoding, writer, bytes.NewReader(content), gzipCompressLevel)
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeLevel reads from reader,writes to writer by specific encoding and compress level
|
// writeLevel reads from reader and writes to writer by specific encoding and compress level.
|
||||||
// the compress level is defined by deflate package
|
// The compress level is defined by deflate package
|
||||||
func writeLevel(encoding string, writer io.Writer, reader io.Reader, level int) (bool, string, error) {
|
func writeLevel(encoding string, writer io.Writer, reader io.Reader, level int) (bool, string, error) {
|
||||||
var outputWriter resetWriter
|
var outputWriter resetWriter
|
||||||
var err error
|
var err error
|
||||||
|
@ -38,7 +38,7 @@ import (
|
|||||||
"github.com/astaxie/beego/pkg/utils"
|
"github.com/astaxie/beego/pkg/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
//commonly used mime-types
|
// Commonly used mime-types
|
||||||
const (
|
const (
|
||||||
ApplicationJSON = "application/json"
|
ApplicationJSON = "application/json"
|
||||||
ApplicationXML = "application/xml"
|
ApplicationXML = "application/xml"
|
||||||
@ -55,7 +55,7 @@ func NewContext() *Context {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Context Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter.
|
// Context Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter.
|
||||||
// BeegoInput and BeegoOutput provides some api to operate request and response more easily.
|
// BeegoInput and BeegoOutput provides an api to operate request and response more easily.
|
||||||
type Context struct {
|
type Context struct {
|
||||||
Input *BeegoInput
|
Input *BeegoInput
|
||||||
Output *BeegoOutput
|
Output *BeegoOutput
|
||||||
@ -64,7 +64,7 @@ type Context struct {
|
|||||||
_xsrfToken string
|
_xsrfToken string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset init Context, BeegoInput and BeegoOutput
|
// Reset initializes Context, BeegoInput and BeegoOutput
|
||||||
func (ctx *Context) Reset(rw http.ResponseWriter, r *http.Request) {
|
func (ctx *Context) Reset(rw http.ResponseWriter, r *http.Request) {
|
||||||
ctx.Request = r
|
ctx.Request = r
|
||||||
if ctx.ResponseWriter == nil {
|
if ctx.ResponseWriter == nil {
|
||||||
@ -76,37 +76,36 @@ func (ctx *Context) Reset(rw http.ResponseWriter, r *http.Request) {
|
|||||||
ctx._xsrfToken = ""
|
ctx._xsrfToken = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redirect does redirection to localurl with http header status code.
|
// Redirect redirects to localurl with http header status code.
|
||||||
func (ctx *Context) Redirect(status int, localurl string) {
|
func (ctx *Context) Redirect(status int, localurl string) {
|
||||||
http.Redirect(ctx.ResponseWriter, ctx.Request, localurl, status)
|
http.Redirect(ctx.ResponseWriter, ctx.Request, localurl, status)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Abort stops this request.
|
// Abort stops the request.
|
||||||
// if beego.ErrorMaps exists, panic body.
|
// If beego.ErrorMaps exists, panic body.
|
||||||
func (ctx *Context) Abort(status int, body string) {
|
func (ctx *Context) Abort(status int, body string) {
|
||||||
ctx.Output.SetStatus(status)
|
ctx.Output.SetStatus(status)
|
||||||
panic(body)
|
panic(body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteString Write string to response body.
|
// WriteString writes a string to response body.
|
||||||
// it sends response body.
|
|
||||||
func (ctx *Context) WriteString(content string) {
|
func (ctx *Context) WriteString(content string) {
|
||||||
ctx.ResponseWriter.Write([]byte(content))
|
ctx.ResponseWriter.Write([]byte(content))
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCookie Get cookie from request by a given key.
|
// GetCookie gets a cookie from a request for a given key.
|
||||||
// It's alias of BeegoInput.Cookie.
|
// (Alias of BeegoInput.Cookie)
|
||||||
func (ctx *Context) GetCookie(key string) string {
|
func (ctx *Context) GetCookie(key string) string {
|
||||||
return ctx.Input.Cookie(key)
|
return ctx.Input.Cookie(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCookie Set cookie for response.
|
// SetCookie sets a cookie for a response.
|
||||||
// It's alias of BeegoOutput.Cookie.
|
// (Alias of BeegoOutput.Cookie)
|
||||||
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
|
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
|
||||||
ctx.Output.Cookie(name, value, others...)
|
ctx.Output.Cookie(name, value, others...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSecureCookie Get secure cookie from request by a given key.
|
// GetSecureCookie gets a secure cookie from a request for a given key.
|
||||||
func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
|
func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
|
||||||
val := ctx.Input.Cookie(key)
|
val := ctx.Input.Cookie(key)
|
||||||
if val == "" {
|
if val == "" {
|
||||||
@ -133,7 +132,7 @@ func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
|
|||||||
return string(res), true
|
return string(res), true
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSecureCookie Set Secure cookie for response.
|
// SetSecureCookie sets a secure cookie for a response.
|
||||||
func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
|
func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
|
||||||
vs := base64.URLEncoding.EncodeToString([]byte(value))
|
vs := base64.URLEncoding.EncodeToString([]byte(value))
|
||||||
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
|
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
|
||||||
@ -144,7 +143,7 @@ func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interf
|
|||||||
ctx.Output.Cookie(name, cookie, others...)
|
ctx.Output.Cookie(name, cookie, others...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// XSRFToken creates a xsrf token string and returns.
|
// XSRFToken creates and returns an xsrf token string
|
||||||
func (ctx *Context) XSRFToken(key string, expire int64) string {
|
func (ctx *Context) XSRFToken(key string, expire int64) string {
|
||||||
if ctx._xsrfToken == "" {
|
if ctx._xsrfToken == "" {
|
||||||
token, ok := ctx.GetSecureCookie(key, "_xsrf")
|
token, ok := ctx.GetSecureCookie(key, "_xsrf")
|
||||||
@ -157,8 +156,8 @@ func (ctx *Context) XSRFToken(key string, expire int64) string {
|
|||||||
return ctx._xsrfToken
|
return ctx._xsrfToken
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckXSRFCookie checks xsrf token in this request is valid or not.
|
// CheckXSRFCookie checks if the XSRF token in this request is valid or not.
|
||||||
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
|
// The token can be provided in the request header in the form "X-Xsrftoken" or "X-CsrfToken"
|
||||||
// or in form field value named as "_xsrf".
|
// or in form field value named as "_xsrf".
|
||||||
func (ctx *Context) CheckXSRFCookie() bool {
|
func (ctx *Context) CheckXSRFCookie() bool {
|
||||||
token := ctx.Input.Query("_xsrf")
|
token := ctx.Input.Query("_xsrf")
|
||||||
@ -196,7 +195,7 @@ func (ctx *Context) RenderMethodResult(result interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Response is a wrapper for the http.ResponseWriter
|
// Response is a wrapper for the http.ResponseWriter
|
||||||
//started set to true if response was written to then don't execute other handler
|
// Started: if true, response was already written to so the other handler will not be executed
|
||||||
type Response struct {
|
type Response struct {
|
||||||
http.ResponseWriter
|
http.ResponseWriter
|
||||||
Started bool
|
Started bool
|
||||||
@ -210,16 +209,16 @@ func (r *Response) reset(rw http.ResponseWriter) {
|
|||||||
r.Started = false
|
r.Started = false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write writes the data to the connection as part of an HTTP reply,
|
// Write writes the data to the connection as part of a HTTP reply,
|
||||||
// and sets `started` to true.
|
// and sets `Started` to true.
|
||||||
// started means the response has sent out.
|
// Started: if true, the response was already sent
|
||||||
func (r *Response) Write(p []byte) (int, error) {
|
func (r *Response) Write(p []byte) (int, error) {
|
||||||
r.Started = true
|
r.Started = true
|
||||||
return r.ResponseWriter.Write(p)
|
return r.ResponseWriter.Write(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteHeader sends an HTTP response header with status code,
|
// WriteHeader sends a HTTP response header with status code,
|
||||||
// and sets `started` to true.
|
// and sets `Started` to true.
|
||||||
func (r *Response) WriteHeader(code int) {
|
func (r *Response) WriteHeader(code int) {
|
||||||
if r.Status > 0 {
|
if r.Status > 0 {
|
||||||
//prevent multiple response.WriteHeader calls
|
//prevent multiple response.WriteHeader calls
|
||||||
|
@ -43,7 +43,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// BeegoInput operates the http request header, data, cookie and body.
|
// BeegoInput operates the http request header, data, cookie and body.
|
||||||
// it also contains router params and current session.
|
// Contains router params and current session.
|
||||||
type BeegoInput struct {
|
type BeegoInput struct {
|
||||||
Context *Context
|
Context *Context
|
||||||
CruSession session.Store
|
CruSession session.Store
|
||||||
@ -56,7 +56,7 @@ type BeegoInput struct {
|
|||||||
RunController reflect.Type
|
RunController reflect.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewInput return BeegoInput generated by Context.
|
// NewInput returns the BeegoInput generated by context.
|
||||||
func NewInput() *BeegoInput {
|
func NewInput() *BeegoInput {
|
||||||
return &BeegoInput{
|
return &BeegoInput{
|
||||||
pnames: make([]string, 0, maxParam),
|
pnames: make([]string, 0, maxParam),
|
||||||
@ -65,7 +65,7 @@ func NewInput() *BeegoInput {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset init the BeegoInput
|
// Reset initializes the BeegoInput
|
||||||
func (input *BeegoInput) Reset(ctx *Context) {
|
func (input *BeegoInput) Reset(ctx *Context) {
|
||||||
input.Context = ctx
|
input.Context = ctx
|
||||||
input.CruSession = nil
|
input.CruSession = nil
|
||||||
@ -77,27 +77,27 @@ func (input *BeegoInput) Reset(ctx *Context) {
|
|||||||
input.RequestBody = []byte{}
|
input.RequestBody = []byte{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Protocol returns request protocol name, such as HTTP/1.1 .
|
// Protocol returns the request protocol name, such as HTTP/1.1 .
|
||||||
func (input *BeegoInput) Protocol() string {
|
func (input *BeegoInput) Protocol() string {
|
||||||
return input.Context.Request.Proto
|
return input.Context.Request.Proto
|
||||||
}
|
}
|
||||||
|
|
||||||
// URI returns full request url with query string, fragment.
|
// URI returns the full request url with query, string and fragment.
|
||||||
func (input *BeegoInput) URI() string {
|
func (input *BeegoInput) URI() string {
|
||||||
return input.Context.Request.RequestURI
|
return input.Context.Request.RequestURI
|
||||||
}
|
}
|
||||||
|
|
||||||
// URL returns request url path (without query string, fragment).
|
// URL returns the request url path (without query, string and fragment).
|
||||||
func (input *BeegoInput) URL() string {
|
func (input *BeegoInput) URL() string {
|
||||||
return input.Context.Request.URL.EscapedPath()
|
return input.Context.Request.URL.EscapedPath()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Site returns base site url as scheme://domain type.
|
// Site returns the base site url as scheme://domain type.
|
||||||
func (input *BeegoInput) Site() string {
|
func (input *BeegoInput) Site() string {
|
||||||
return input.Scheme() + "://" + input.Domain()
|
return input.Scheme() + "://" + input.Domain()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scheme returns request scheme as "http" or "https".
|
// Scheme returns the request scheme as "http" or "https".
|
||||||
func (input *BeegoInput) Scheme() string {
|
func (input *BeegoInput) Scheme() string {
|
||||||
if scheme := input.Header("X-Forwarded-Proto"); scheme != "" {
|
if scheme := input.Header("X-Forwarded-Proto"); scheme != "" {
|
||||||
return scheme
|
return scheme
|
||||||
@ -111,14 +111,13 @@ func (input *BeegoInput) Scheme() string {
|
|||||||
return "https"
|
return "https"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Domain returns host name.
|
// Domain returns the host name (alias of host method)
|
||||||
// Alias of Host method.
|
|
||||||
func (input *BeegoInput) Domain() string {
|
func (input *BeegoInput) Domain() string {
|
||||||
return input.Host()
|
return input.Host()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Host returns host name.
|
// Host returns the host name.
|
||||||
// if no host info in request, return localhost.
|
// If no host info in request, return localhost.
|
||||||
func (input *BeegoInput) Host() string {
|
func (input *BeegoInput) Host() string {
|
||||||
if input.Context.Request.Host != "" {
|
if input.Context.Request.Host != "" {
|
||||||
if hostPart, _, err := net.SplitHostPort(input.Context.Request.Host); err == nil {
|
if hostPart, _, err := net.SplitHostPort(input.Context.Request.Host); err == nil {
|
||||||
@ -134,7 +133,7 @@ func (input *BeegoInput) Method() string {
|
|||||||
return input.Context.Request.Method
|
return input.Context.Request.Method
|
||||||
}
|
}
|
||||||
|
|
||||||
// Is returns boolean of this request is on given method, such as Is("POST").
|
// Is returns the boolean value of this request is on given method, such as Is("POST").
|
||||||
func (input *BeegoInput) Is(method string) bool {
|
func (input *BeegoInput) Is(method string) bool {
|
||||||
return input.Method() == method
|
return input.Method() == method
|
||||||
}
|
}
|
||||||
@ -174,7 +173,7 @@ func (input *BeegoInput) IsPatch() bool {
|
|||||||
return input.Is("PATCH")
|
return input.Is("PATCH")
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsAjax returns boolean of this request is generated by ajax.
|
// IsAjax returns boolean of is this request generated by ajax.
|
||||||
func (input *BeegoInput) IsAjax() bool {
|
func (input *BeegoInput) IsAjax() bool {
|
||||||
return input.Header("X-Requested-With") == "XMLHttpRequest"
|
return input.Header("X-Requested-With") == "XMLHttpRequest"
|
||||||
}
|
}
|
||||||
@ -251,7 +250,7 @@ func (input *BeegoInput) Refer() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SubDomains returns sub domain string.
|
// SubDomains returns sub domain string.
|
||||||
// if aa.bb.domain.com, returns aa.bb .
|
// if aa.bb.domain.com, returns aa.bb
|
||||||
func (input *BeegoInput) SubDomains() string {
|
func (input *BeegoInput) SubDomains() string {
|
||||||
parts := strings.Split(input.Host(), ".")
|
parts := strings.Split(input.Host(), ".")
|
||||||
if len(parts) >= 3 {
|
if len(parts) >= 3 {
|
||||||
@ -306,7 +305,7 @@ func (input *BeegoInput) Params() map[string]string {
|
|||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetParam will set the param with key and value
|
// SetParam sets the param with key and value
|
||||||
func (input *BeegoInput) SetParam(key, val string) {
|
func (input *BeegoInput) SetParam(key, val string) {
|
||||||
// check if already exists
|
// check if already exists
|
||||||
for i, v := range input.pnames {
|
for i, v := range input.pnames {
|
||||||
@ -319,9 +318,8 @@ func (input *BeegoInput) SetParam(key, val string) {
|
|||||||
input.pnames = append(input.pnames, key)
|
input.pnames = append(input.pnames, key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResetParams clears any of the input's Params
|
// ResetParams clears any of the input's params
|
||||||
// This function is used to clear parameters so they may be reset between filter
|
// Used to clear parameters so they may be reset between filter passes.
|
||||||
// passes.
|
|
||||||
func (input *BeegoInput) ResetParams() {
|
func (input *BeegoInput) ResetParams() {
|
||||||
input.pnames = input.pnames[:0]
|
input.pnames = input.pnames[:0]
|
||||||
input.pvalues = input.pvalues[:0]
|
input.pvalues = input.pvalues[:0]
|
||||||
@ -391,7 +389,7 @@ func (input *BeegoInput) CopyBody(MaxMemory int64) []byte {
|
|||||||
return requestbody
|
return requestbody
|
||||||
}
|
}
|
||||||
|
|
||||||
// Data return the implicit data in the input
|
// Data returns the implicit data in the input
|
||||||
func (input *BeegoInput) Data() map[interface{}]interface{} {
|
func (input *BeegoInput) Data() map[interface{}]interface{} {
|
||||||
input.dataLock.Lock()
|
input.dataLock.Lock()
|
||||||
defer input.dataLock.Unlock()
|
defer input.dataLock.Unlock()
|
||||||
@ -412,7 +410,7 @@ func (input *BeegoInput) GetData(key interface{}) interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetData stores data with given key in this context.
|
// SetData stores data with given key in this context.
|
||||||
// This data are only available in this context.
|
// This data is only available in this context.
|
||||||
func (input *BeegoInput) SetData(key, val interface{}) {
|
func (input *BeegoInput) SetData(key, val interface{}) {
|
||||||
input.dataLock.Lock()
|
input.dataLock.Lock()
|
||||||
defer input.dataLock.Unlock()
|
defer input.dataLock.Unlock()
|
||||||
|
@ -42,12 +42,12 @@ type BeegoOutput struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewOutput returns new BeegoOutput.
|
// NewOutput returns new BeegoOutput.
|
||||||
// it contains nothing now.
|
// Empty when initialized
|
||||||
func NewOutput() *BeegoOutput {
|
func NewOutput() *BeegoOutput {
|
||||||
return &BeegoOutput{}
|
return &BeegoOutput{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset init BeegoOutput
|
// Reset initializes BeegoOutput
|
||||||
func (output *BeegoOutput) Reset(ctx *Context) {
|
func (output *BeegoOutput) Reset(ctx *Context) {
|
||||||
output.Context = ctx
|
output.Context = ctx
|
||||||
output.Status = 0
|
output.Status = 0
|
||||||
@ -58,9 +58,9 @@ func (output *BeegoOutput) Header(key, val string) {
|
|||||||
output.Context.ResponseWriter.Header().Set(key, val)
|
output.Context.ResponseWriter.Header().Set(key, val)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Body sets response body content.
|
// Body sets the response body content.
|
||||||
// if EnableGzip, compress content string.
|
// if EnableGzip, content is compressed.
|
||||||
// it sends out response body directly.
|
// Sends out response body directly.
|
||||||
func (output *BeegoOutput) Body(content []byte) error {
|
func (output *BeegoOutput) Body(content []byte) error {
|
||||||
var encoding string
|
var encoding string
|
||||||
var buf = &bytes.Buffer{}
|
var buf = &bytes.Buffer{}
|
||||||
@ -85,8 +85,8 @@ func (output *BeegoOutput) Body(content []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cookie sets cookie value via given key.
|
// Cookie sets a cookie value via given key.
|
||||||
// others are ordered as cookie's max age time, path,domain, secure and httponly.
|
// others: used to set a cookie's max age time, path,domain, secure and httponly.
|
||||||
func (output *BeegoOutput) Cookie(name string, value string, others ...interface{}) {
|
func (output *BeegoOutput) Cookie(name string, value string, others ...interface{}) {
|
||||||
var b bytes.Buffer
|
var b bytes.Buffer
|
||||||
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
|
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
|
||||||
@ -183,7 +183,7 @@ func errorRenderer(err error) Renderer {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// JSON writes json to response body.
|
// JSON writes json to the response body.
|
||||||
// if encoding is true, it converts utf-8 to \u0000 type.
|
// if encoding is true, it converts utf-8 to \u0000 type.
|
||||||
func (output *BeegoOutput) JSON(data interface{}, hasIndent bool, encoding bool) error {
|
func (output *BeegoOutput) JSON(data interface{}, hasIndent bool, encoding bool) error {
|
||||||
output.Header("Content-Type", "application/json; charset=utf-8")
|
output.Header("Content-Type", "application/json; charset=utf-8")
|
||||||
@ -204,7 +204,7 @@ func (output *BeegoOutput) JSON(data interface{}, hasIndent bool, encoding bool)
|
|||||||
return output.Body(content)
|
return output.Body(content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// YAML writes yaml to response body.
|
// YAML writes yaml to the response body.
|
||||||
func (output *BeegoOutput) YAML(data interface{}) error {
|
func (output *BeegoOutput) YAML(data interface{}) error {
|
||||||
output.Header("Content-Type", "application/x-yaml; charset=utf-8")
|
output.Header("Content-Type", "application/x-yaml; charset=utf-8")
|
||||||
var content []byte
|
var content []byte
|
||||||
@ -217,7 +217,7 @@ func (output *BeegoOutput) YAML(data interface{}) error {
|
|||||||
return output.Body(content)
|
return output.Body(content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JSONP writes jsonp to response body.
|
// JSONP writes jsonp to the response body.
|
||||||
func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error {
|
func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error {
|
||||||
output.Header("Content-Type", "application/javascript; charset=utf-8")
|
output.Header("Content-Type", "application/javascript; charset=utf-8")
|
||||||
var content []byte
|
var content []byte
|
||||||
@ -243,7 +243,7 @@ func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error {
|
|||||||
return output.Body(callbackContent.Bytes())
|
return output.Body(callbackContent.Bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
// XML writes xml string to response body.
|
// XML writes xml string to the response body.
|
||||||
func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
|
func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
|
||||||
output.Header("Content-Type", "application/xml; charset=utf-8")
|
output.Header("Content-Type", "application/xml; charset=utf-8")
|
||||||
var content []byte
|
var content []byte
|
||||||
@ -260,7 +260,7 @@ func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
|
|||||||
return output.Body(content)
|
return output.Body(content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
|
// ServeFormatted serves YAML, XML or JSON, depending on the value of the Accept header
|
||||||
func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) {
|
func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) {
|
||||||
accept := output.Context.Input.Header("Accept")
|
accept := output.Context.Input.Header("Accept")
|
||||||
switch accept {
|
switch accept {
|
||||||
@ -274,7 +274,7 @@ func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasE
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Download forces response for download file.
|
// Download forces response for download file.
|
||||||
// it prepares the download response header automatically.
|
// Prepares the download response header automatically.
|
||||||
func (output *BeegoOutput) Download(file string, filename ...string) {
|
func (output *BeegoOutput) Download(file string, filename ...string) {
|
||||||
// check get file error, file not found or other error.
|
// check get file error, file not found or other error.
|
||||||
if _, err := os.Stat(file); err != nil {
|
if _, err := os.Stat(file); err != nil {
|
||||||
@ -323,61 +323,61 @@ func (output *BeegoOutput) ContentType(ext string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetStatus sets response status code.
|
// SetStatus sets the response status code.
|
||||||
// It writes response header directly.
|
// Writes response header directly.
|
||||||
func (output *BeegoOutput) SetStatus(status int) {
|
func (output *BeegoOutput) SetStatus(status int) {
|
||||||
output.Status = status
|
output.Status = status
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsCachable returns boolean of this request is cached.
|
// IsCachable returns boolean of if this request is cached.
|
||||||
// HTTP 304 means cached.
|
// HTTP 304 means cached.
|
||||||
func (output *BeegoOutput) IsCachable() bool {
|
func (output *BeegoOutput) IsCachable() bool {
|
||||||
return output.Status >= 200 && output.Status < 300 || output.Status == 304
|
return output.Status >= 200 && output.Status < 300 || output.Status == 304
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsEmpty returns boolean of this request is empty.
|
// IsEmpty returns boolean of if this request is empty.
|
||||||
// HTTP 201,204 and 304 means empty.
|
// HTTP 201,204 and 304 means empty.
|
||||||
func (output *BeegoOutput) IsEmpty() bool {
|
func (output *BeegoOutput) IsEmpty() bool {
|
||||||
return output.Status == 201 || output.Status == 204 || output.Status == 304
|
return output.Status == 201 || output.Status == 204 || output.Status == 304
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsOk returns boolean of this request runs well.
|
// IsOk returns boolean of if this request was ok.
|
||||||
// HTTP 200 means ok.
|
// HTTP 200 means ok.
|
||||||
func (output *BeegoOutput) IsOk() bool {
|
func (output *BeegoOutput) IsOk() bool {
|
||||||
return output.Status == 200
|
return output.Status == 200
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsSuccessful returns boolean of this request runs successfully.
|
// IsSuccessful returns boolean of this request was successful.
|
||||||
// HTTP 2xx means ok.
|
// HTTP 2xx means ok.
|
||||||
func (output *BeegoOutput) IsSuccessful() bool {
|
func (output *BeegoOutput) IsSuccessful() bool {
|
||||||
return output.Status >= 200 && output.Status < 300
|
return output.Status >= 200 && output.Status < 300
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsRedirect returns boolean of this request is redirection header.
|
// IsRedirect returns boolean of if this request is redirected.
|
||||||
// HTTP 301,302,307 means redirection.
|
// HTTP 301,302,307 means redirection.
|
||||||
func (output *BeegoOutput) IsRedirect() bool {
|
func (output *BeegoOutput) IsRedirect() bool {
|
||||||
return output.Status == 301 || output.Status == 302 || output.Status == 303 || output.Status == 307
|
return output.Status == 301 || output.Status == 302 || output.Status == 303 || output.Status == 307
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsForbidden returns boolean of this request is forbidden.
|
// IsForbidden returns boolean of if this request is forbidden.
|
||||||
// HTTP 403 means forbidden.
|
// HTTP 403 means forbidden.
|
||||||
func (output *BeegoOutput) IsForbidden() bool {
|
func (output *BeegoOutput) IsForbidden() bool {
|
||||||
return output.Status == 403
|
return output.Status == 403
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsNotFound returns boolean of this request is not found.
|
// IsNotFound returns boolean of if this request is not found.
|
||||||
// HTTP 404 means not found.
|
// HTTP 404 means not found.
|
||||||
func (output *BeegoOutput) IsNotFound() bool {
|
func (output *BeegoOutput) IsNotFound() bool {
|
||||||
return output.Status == 404
|
return output.Status == 404
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsClientError returns boolean of this request client sends error data.
|
// IsClientError returns boolean of if this request client sends error data.
|
||||||
// HTTP 4xx means client error.
|
// HTTP 4xx means client error.
|
||||||
func (output *BeegoOutput) IsClientError() bool {
|
func (output *BeegoOutput) IsClientError() bool {
|
||||||
return output.Status >= 400 && output.Status < 500
|
return output.Status >= 400 && output.Status < 500
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsServerError returns boolean of this server handler errors.
|
// IsServerError returns boolean of if this server handler errors.
|
||||||
// HTTP 5xx means server internal error.
|
// HTTP 5xx means server internal error.
|
||||||
func (output *BeegoOutput) IsServerError() bool {
|
func (output *BeegoOutput) IsServerError() bool {
|
||||||
return output.Status >= 500 && output.Status < 600
|
return output.Status >= 500 && output.Status < 600
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package context
|
package context
|
||||||
|
|
||||||
// Renderer defines an http response renderer
|
// Renderer defines a http response renderer
|
||||||
type Renderer interface {
|
type Renderer interface {
|
||||||
Render(ctx *Context)
|
Render(ctx *Context)
|
||||||
}
|
}
|
||||||
|
@ -7,21 +7,21 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
//BadRequest indicates http error 400
|
//BadRequest indicates HTTP error 400
|
||||||
BadRequest StatusCode = http.StatusBadRequest
|
BadRequest StatusCode = http.StatusBadRequest
|
||||||
|
|
||||||
//NotFound indicates http error 404
|
//NotFound indicates HTTP error 404
|
||||||
NotFound StatusCode = http.StatusNotFound
|
NotFound StatusCode = http.StatusNotFound
|
||||||
)
|
)
|
||||||
|
|
||||||
// StatusCode sets the http response status code
|
// StatusCode sets the HTTP response status code
|
||||||
type StatusCode int
|
type StatusCode int
|
||||||
|
|
||||||
func (s StatusCode) Error() string {
|
func (s StatusCode) Error() string {
|
||||||
return strconv.Itoa(int(s))
|
return strconv.Itoa(int(s))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render sets the http status code
|
// Render sets the HTTP status code
|
||||||
func (s StatusCode) Render(ctx *Context) {
|
func (s StatusCode) Render(ctx *Context) {
|
||||||
ctx.Output.SetStatus(int(s))
|
ctx.Output.SetStatus(int(s))
|
||||||
}
|
}
|
||||||
|
@ -29,8 +29,8 @@ type Server struct {
|
|||||||
terminalChan chan error
|
terminalChan chan error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serve accepts incoming connections on the Listener l,
|
// Serve accepts incoming connections on the Listener l
|
||||||
// creating a new service goroutine for each.
|
// and creates a new service goroutine for each.
|
||||||
// The service goroutines read requests and then call srv.Handler to reply to them.
|
// The service goroutines read requests and then call srv.Handler to reply to them.
|
||||||
func (srv *Server) Serve() (err error) {
|
func (srv *Server) Serve() (err error) {
|
||||||
srv.state = StateRunning
|
srv.state = StateRunning
|
||||||
|
@ -73,14 +73,14 @@ func createDefaultCookie() {
|
|||||||
defaultCookieJar, _ = cookiejar.New(nil)
|
defaultCookieJar, _ = cookiejar.New(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetDefaultSetting Overwrite default settings
|
// SetDefaultSetting overwrites default settings
|
||||||
func SetDefaultSetting(setting BeegoHTTPSettings) {
|
func SetDefaultSetting(setting BeegoHTTPSettings) {
|
||||||
settingMutex.Lock()
|
settingMutex.Lock()
|
||||||
defer settingMutex.Unlock()
|
defer settingMutex.Unlock()
|
||||||
defaultSetting = setting
|
defaultSetting = setting
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewBeegoRequest return *BeegoHttpRequest with specific method
|
// NewBeegoRequest returns *BeegoHttpRequest with specific method
|
||||||
func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest {
|
func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest {
|
||||||
var resp http.Response
|
var resp http.Response
|
||||||
u, err := url.Parse(rawurl)
|
u, err := url.Parse(rawurl)
|
||||||
@ -147,7 +147,7 @@ type BeegoHTTPSettings struct {
|
|||||||
RetryDelay time.Duration
|
RetryDelay time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// BeegoHTTPRequest provides more useful methods for requesting one url than http.Request.
|
// BeegoHTTPRequest provides more useful methods than http.Request for requesting a url.
|
||||||
type BeegoHTTPRequest struct {
|
type BeegoHTTPRequest struct {
|
||||||
url string
|
url string
|
||||||
req *http.Request
|
req *http.Request
|
||||||
@ -159,12 +159,12 @@ type BeegoHTTPRequest struct {
|
|||||||
dump []byte
|
dump []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRequest return the request object
|
// GetRequest returns the request object
|
||||||
func (b *BeegoHTTPRequest) GetRequest() *http.Request {
|
func (b *BeegoHTTPRequest) GetRequest() *http.Request {
|
||||||
return b.req
|
return b.req
|
||||||
}
|
}
|
||||||
|
|
||||||
// Setting Change request settings
|
// Setting changes request settings
|
||||||
func (b *BeegoHTTPRequest) Setting(setting BeegoHTTPSettings) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) Setting(setting BeegoHTTPSettings) *BeegoHTTPRequest {
|
||||||
b.setting = setting
|
b.setting = setting
|
||||||
return b
|
return b
|
||||||
@ -195,26 +195,27 @@ func (b *BeegoHTTPRequest) Debug(isdebug bool) *BeegoHTTPRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Retries sets Retries times.
|
// Retries sets Retries times.
|
||||||
// default is 0 means no retried.
|
// default is 0 (never retries)
|
||||||
// -1 means retried forever.
|
// -1 retry indefinitely (forever)
|
||||||
// others means retried times.
|
// Other numbers specify the exact retry amount
|
||||||
func (b *BeegoHTTPRequest) Retries(times int) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) Retries(times int) *BeegoHTTPRequest {
|
||||||
b.setting.Retries = times
|
b.setting.Retries = times
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RetryDelay sets the time to sleep between reconnection attempts
|
||||||
func (b *BeegoHTTPRequest) RetryDelay(delay time.Duration) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) RetryDelay(delay time.Duration) *BeegoHTTPRequest {
|
||||||
b.setting.RetryDelay = delay
|
b.setting.RetryDelay = delay
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// DumpBody setting whether need to Dump the Body.
|
// DumpBody sets the DumbBody field
|
||||||
func (b *BeegoHTTPRequest) DumpBody(isdump bool) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) DumpBody(isdump bool) *BeegoHTTPRequest {
|
||||||
b.setting.DumpBody = isdump
|
b.setting.DumpBody = isdump
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// DumpRequest return the DumpRequest
|
// DumpRequest returns the DumpRequest
|
||||||
func (b *BeegoHTTPRequest) DumpRequest() []byte {
|
func (b *BeegoHTTPRequest) DumpRequest() []byte {
|
||||||
return b.dump
|
return b.dump
|
||||||
}
|
}
|
||||||
@ -226,13 +227,13 @@ func (b *BeegoHTTPRequest) SetTimeout(connectTimeout, readWriteTimeout time.Dura
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTLSClientConfig sets tls connection configurations if visiting https url.
|
// SetTLSClientConfig sets TLS connection configuration if visiting HTTPS url.
|
||||||
func (b *BeegoHTTPRequest) SetTLSClientConfig(config *tls.Config) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) SetTLSClientConfig(config *tls.Config) *BeegoHTTPRequest {
|
||||||
b.setting.TLSClientConfig = config
|
b.setting.TLSClientConfig = config
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// Header add header item string in request.
|
// Header adds header item string in request.
|
||||||
func (b *BeegoHTTPRequest) Header(key, value string) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) Header(key, value string) *BeegoHTTPRequest {
|
||||||
b.req.Header.Set(key, value)
|
b.req.Header.Set(key, value)
|
||||||
return b
|
return b
|
||||||
@ -244,7 +245,7 @@ func (b *BeegoHTTPRequest) SetHost(host string) *BeegoHTTPRequest {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetProtocolVersion Set the protocol version for incoming requests.
|
// SetProtocolVersion sets the protocol version for incoming requests.
|
||||||
// Client requests always use HTTP/1.1.
|
// Client requests always use HTTP/1.1.
|
||||||
func (b *BeegoHTTPRequest) SetProtocolVersion(vers string) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) SetProtocolVersion(vers string) *BeegoHTTPRequest {
|
||||||
if len(vers) == 0 {
|
if len(vers) == 0 {
|
||||||
@ -261,19 +262,19 @@ func (b *BeegoHTTPRequest) SetProtocolVersion(vers string) *BeegoHTTPRequest {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCookie add cookie into request.
|
// SetCookie adds a cookie to the request.
|
||||||
func (b *BeegoHTTPRequest) SetCookie(cookie *http.Cookie) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) SetCookie(cookie *http.Cookie) *BeegoHTTPRequest {
|
||||||
b.req.Header.Add("Cookie", cookie.String())
|
b.req.Header.Add("Cookie", cookie.String())
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTransport set the setting transport
|
// SetTransport sets the transport field
|
||||||
func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPRequest {
|
||||||
b.setting.Transport = transport
|
b.setting.Transport = transport
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetProxy set the http proxy
|
// SetProxy sets the HTTP proxy
|
||||||
// example:
|
// example:
|
||||||
//
|
//
|
||||||
// func(req *http.Request) (*url.URL, error) {
|
// func(req *http.Request) (*url.URL, error) {
|
||||||
@ -305,14 +306,14 @@ func (b *BeegoHTTPRequest) Param(key, value string) *BeegoHTTPRequest {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostFile add a post file to the request
|
// PostFile adds a post file to the request
|
||||||
func (b *BeegoHTTPRequest) PostFile(formname, filename string) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) PostFile(formname, filename string) *BeegoHTTPRequest {
|
||||||
b.files[formname] = filename
|
b.files[formname] = filename
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// Body adds request raw body.
|
// Body adds request raw body.
|
||||||
// it supports string and []byte.
|
// Supports string and []byte.
|
||||||
func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest {
|
func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest {
|
||||||
switch t := data.(type) {
|
switch t := data.(type) {
|
||||||
case string:
|
case string:
|
||||||
@ -327,7 +328,7 @@ func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// XMLBody adds request raw body encoding by XML.
|
// XMLBody adds the request raw body encoded in XML.
|
||||||
func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
||||||
if b.req.Body == nil && obj != nil {
|
if b.req.Body == nil && obj != nil {
|
||||||
byts, err := xml.Marshal(obj)
|
byts, err := xml.Marshal(obj)
|
||||||
@ -341,7 +342,7 @@ func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
|||||||
return b, nil
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// YAMLBody adds request raw body encoding by YAML.
|
// YAMLBody adds the request raw body encoded in YAML.
|
||||||
func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
||||||
if b.req.Body == nil && obj != nil {
|
if b.req.Body == nil && obj != nil {
|
||||||
byts, err := yaml.Marshal(obj)
|
byts, err := yaml.Marshal(obj)
|
||||||
@ -355,7 +356,7 @@ func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error)
|
|||||||
return b, nil
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// JSONBody adds request raw body encoding by JSON.
|
// JSONBody adds the request raw body encoded in JSON.
|
||||||
func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error) {
|
||||||
if b.req.Body == nil && obj != nil {
|
if b.req.Body == nil && obj != nil {
|
||||||
byts, err := json.Marshal(obj)
|
byts, err := json.Marshal(obj)
|
||||||
@ -437,7 +438,7 @@ func (b *BeegoHTTPRequest) getResponse() (*http.Response, error) {
|
|||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DoRequest will do the client.Do
|
// DoRequest executes client.Do
|
||||||
func (b *BeegoHTTPRequest) DoRequest() (resp *http.Response, err error) {
|
func (b *BeegoHTTPRequest) DoRequest() (resp *http.Response, err error) {
|
||||||
var paramBody string
|
var paramBody string
|
||||||
if len(b.params) > 0 {
|
if len(b.params) > 0 {
|
||||||
@ -530,7 +531,7 @@ func (b *BeegoHTTPRequest) DoRequest() (resp *http.Response, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// String returns the body string in response.
|
// String returns the body string in response.
|
||||||
// it calls Response inner.
|
// Calls Response inner.
|
||||||
func (b *BeegoHTTPRequest) String() (string, error) {
|
func (b *BeegoHTTPRequest) String() (string, error) {
|
||||||
data, err := b.Bytes()
|
data, err := b.Bytes()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -541,7 +542,7 @@ func (b *BeegoHTTPRequest) String() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Bytes returns the body []byte in response.
|
// Bytes returns the body []byte in response.
|
||||||
// it calls Response inner.
|
// Calls Response inner.
|
||||||
func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
|
func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
|
||||||
if b.body != nil {
|
if b.body != nil {
|
||||||
return b.body, nil
|
return b.body, nil
|
||||||
@ -567,7 +568,7 @@ func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToFile saves the body data in response to one file.
|
// ToFile saves the body data in response to one file.
|
||||||
// it calls Response inner.
|
// Calls Response inner.
|
||||||
func (b *BeegoHTTPRequest) ToFile(filename string) error {
|
func (b *BeegoHTTPRequest) ToFile(filename string) error {
|
||||||
resp, err := b.getResponse()
|
resp, err := b.getResponse()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -590,7 +591,7 @@ func (b *BeegoHTTPRequest) ToFile(filename string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Check that the file directory exists, there is no automatically created
|
// Check if the file directory exists. If it doesn't then it's created
|
||||||
func pathExistAndMkdir(filename string) (err error) {
|
func pathExistAndMkdir(filename string) (err error) {
|
||||||
filename = path.Dir(filename)
|
filename = path.Dir(filename)
|
||||||
_, err = os.Stat(filename)
|
_, err = os.Stat(filename)
|
||||||
@ -607,7 +608,7 @@ func pathExistAndMkdir(filename string) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToJSON returns the map that marshals from the body bytes as json in response.
|
// ToJSON returns the map that marshals from the body bytes as json in response.
|
||||||
// it calls Response inner.
|
// Calls Response inner.
|
||||||
func (b *BeegoHTTPRequest) ToJSON(v interface{}) error {
|
func (b *BeegoHTTPRequest) ToJSON(v interface{}) error {
|
||||||
data, err := b.Bytes()
|
data, err := b.Bytes()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -617,7 +618,7 @@ func (b *BeegoHTTPRequest) ToJSON(v interface{}) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToXML returns the map that marshals from the body bytes as xml in response .
|
// ToXML returns the map that marshals from the body bytes as xml in response .
|
||||||
// it calls Response inner.
|
// Calls Response inner.
|
||||||
func (b *BeegoHTTPRequest) ToXML(v interface{}) error {
|
func (b *BeegoHTTPRequest) ToXML(v interface{}) error {
|
||||||
data, err := b.Bytes()
|
data, err := b.Bytes()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -627,7 +628,7 @@ func (b *BeegoHTTPRequest) ToXML(v interface{}) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToYAML returns the map that marshals from the body bytes as yaml in response .
|
// ToYAML returns the map that marshals from the body bytes as yaml in response .
|
||||||
// it calls Response inner.
|
// Calls Response inner.
|
||||||
func (b *BeegoHTTPRequest) ToYAML(v interface{}) error {
|
func (b *BeegoHTTPRequest) ToYAML(v interface{}) error {
|
||||||
data, err := b.Bytes()
|
data, err := b.Bytes()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -636,7 +637,7 @@ func (b *BeegoHTTPRequest) ToYAML(v interface{}) error {
|
|||||||
return yaml.Unmarshal(data, v)
|
return yaml.Unmarshal(data, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Response executes request client gets response mannually.
|
// Response executes request client gets response manually.
|
||||||
func (b *BeegoHTTPRequest) Response() (*http.Response, error) {
|
func (b *BeegoHTTPRequest) Response() (*http.Response, error) {
|
||||||
return b.getResponse()
|
return b.getResponse()
|
||||||
}
|
}
|
||||||
|
@ -28,7 +28,7 @@ const (
|
|||||||
jsonFormat = "JSON_FORMAT"
|
jsonFormat = "JSON_FORMAT"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AccessLogRecord struct for holding access log data.
|
// AccessLogRecord is astruct for holding access log data.
|
||||||
type AccessLogRecord struct {
|
type AccessLogRecord struct {
|
||||||
RemoteAddr string `json:"remote_addr"`
|
RemoteAddr string `json:"remote_addr"`
|
||||||
RequestTime time.Time `json:"request_time"`
|
RequestTime time.Time `json:"request_time"`
|
||||||
|
@ -11,9 +11,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// CacheSize set the flush size
|
// CacheSize sets the flush size
|
||||||
CacheSize int = 64
|
CacheSize int = 64
|
||||||
// Delimiter define the topic delimiter
|
// Delimiter defines the topic delimiter
|
||||||
Delimiter string = "##"
|
Delimiter string = "##"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -31,7 +31,7 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// aliLSWriter implements LoggerInterface.
|
// aliLSWriter implements LoggerInterface.
|
||||||
// it writes messages in keep-live tcp connection.
|
// Writes messages in keep-live tcp connection.
|
||||||
type aliLSWriter struct {
|
type aliLSWriter struct {
|
||||||
store *LogStore
|
store *LogStore
|
||||||
group []*LogGroup
|
group []*LogGroup
|
||||||
@ -41,14 +41,14 @@ type aliLSWriter struct {
|
|||||||
Config
|
Config
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewAliLS create a new Logger
|
// NewAliLS creates a new Logger
|
||||||
func NewAliLS() logs.Logger {
|
func NewAliLS() logs.Logger {
|
||||||
alils := new(aliLSWriter)
|
alils := new(aliLSWriter)
|
||||||
alils.Level = logs.LevelTrace
|
alils.Level = logs.LevelTrace
|
||||||
return alils
|
return alils
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init parse config and init struct
|
// Init parses config and initializes struct
|
||||||
func (c *aliLSWriter) Init(jsonConfig string) (err error) {
|
func (c *aliLSWriter) Init(jsonConfig string) (err error) {
|
||||||
|
|
||||||
json.Unmarshal([]byte(jsonConfig), c)
|
json.Unmarshal([]byte(jsonConfig), c)
|
||||||
@ -101,8 +101,8 @@ func (c *aliLSWriter) Init(jsonConfig string) (err error) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write message in connection.
|
// WriteMsg writes a message in connection.
|
||||||
// if connection is down, try to re-connect.
|
// If connection is down, try to re-connect.
|
||||||
func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error) {
|
func (c *aliLSWriter) WriteMsg(when time.Time, msg string, level int) (err error) {
|
||||||
|
|
||||||
if level > c.Level {
|
if level > c.Level {
|
||||||
|
@ -4,10 +4,10 @@ const (
|
|||||||
version = "0.5.0" // SDK version
|
version = "0.5.0" // SDK version
|
||||||
signatureMethod = "hmac-sha1" // Signature method
|
signatureMethod = "hmac-sha1" // Signature method
|
||||||
|
|
||||||
// OffsetNewest stands for the log head offset, i.e. the offset that will be
|
// OffsetNewest is the log head offset, i.e. the offset that will be
|
||||||
// assigned to the next message that will be produced to the shard.
|
// assigned to the next message that will be produced to the shard.
|
||||||
OffsetNewest = "end"
|
OffsetNewest = "end"
|
||||||
// OffsetOldest stands for the oldest offset available on the logstore for a
|
// OffsetOldest is the the oldest offset available on the logstore for a
|
||||||
// shard.
|
// shard.
|
||||||
OffsetOldest = "begin"
|
OffsetOldest = "begin"
|
||||||
)
|
)
|
||||||
|
@ -31,13 +31,13 @@ type Log struct {
|
|||||||
// Reset the Log
|
// Reset the Log
|
||||||
func (m *Log) Reset() { *m = Log{} }
|
func (m *Log) Reset() { *m = Log{} }
|
||||||
|
|
||||||
// String return the Compact Log
|
// String returns the Compact Log
|
||||||
func (m *Log) String() string { return proto.CompactTextString(m) }
|
func (m *Log) String() string { return proto.CompactTextString(m) }
|
||||||
|
|
||||||
// ProtoMessage not implemented
|
// ProtoMessage not implemented
|
||||||
func (*Log) ProtoMessage() {}
|
func (*Log) ProtoMessage() {}
|
||||||
|
|
||||||
// GetTime return the Log's Time
|
// GetTime returns the Log's Time
|
||||||
func (m *Log) GetTime() uint32 {
|
func (m *Log) GetTime() uint32 {
|
||||||
if m != nil && m.Time != nil {
|
if m != nil && m.Time != nil {
|
||||||
return *m.Time
|
return *m.Time
|
||||||
@ -45,7 +45,7 @@ func (m *Log) GetTime() uint32 {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetContents return the Log's Contents
|
// GetContents returns the Log's Contents
|
||||||
func (m *Log) GetContents() []*LogContent {
|
func (m *Log) GetContents() []*LogContent {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.Contents
|
return m.Contents
|
||||||
@ -53,7 +53,7 @@ func (m *Log) GetContents() []*LogContent {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LogContent define the Log content struct
|
// LogContent defines the Log content struct
|
||||||
type LogContent struct {
|
type LogContent struct {
|
||||||
Key *string `protobuf:"bytes,1,req,name=Key" json:"Key,omitempty"`
|
Key *string `protobuf:"bytes,1,req,name=Key" json:"Key,omitempty"`
|
||||||
Value *string `protobuf:"bytes,2,req,name=Value" json:"Value,omitempty"`
|
Value *string `protobuf:"bytes,2,req,name=Value" json:"Value,omitempty"`
|
||||||
@ -63,13 +63,13 @@ type LogContent struct {
|
|||||||
// Reset LogContent
|
// Reset LogContent
|
||||||
func (m *LogContent) Reset() { *m = LogContent{} }
|
func (m *LogContent) Reset() { *m = LogContent{} }
|
||||||
|
|
||||||
// String return the compact text
|
// String returns the compact text
|
||||||
func (m *LogContent) String() string { return proto.CompactTextString(m) }
|
func (m *LogContent) String() string { return proto.CompactTextString(m) }
|
||||||
|
|
||||||
// ProtoMessage not implemented
|
// ProtoMessage not implemented
|
||||||
func (*LogContent) ProtoMessage() {}
|
func (*LogContent) ProtoMessage() {}
|
||||||
|
|
||||||
// GetKey return the Key
|
// GetKey returns the key
|
||||||
func (m *LogContent) GetKey() string {
|
func (m *LogContent) GetKey() string {
|
||||||
if m != nil && m.Key != nil {
|
if m != nil && m.Key != nil {
|
||||||
return *m.Key
|
return *m.Key
|
||||||
@ -77,7 +77,7 @@ func (m *LogContent) GetKey() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetValue return the Value
|
// GetValue returns the value
|
||||||
func (m *LogContent) GetValue() string {
|
func (m *LogContent) GetValue() string {
|
||||||
if m != nil && m.Value != nil {
|
if m != nil && m.Value != nil {
|
||||||
return *m.Value
|
return *m.Value
|
||||||
@ -85,7 +85,7 @@ func (m *LogContent) GetValue() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// LogGroup define the logs struct
|
// LogGroup defines the logs struct
|
||||||
type LogGroup struct {
|
type LogGroup struct {
|
||||||
Logs []*Log `protobuf:"bytes,1,rep,name=Logs" json:"Logs,omitempty"`
|
Logs []*Log `protobuf:"bytes,1,rep,name=Logs" json:"Logs,omitempty"`
|
||||||
Reserved *string `protobuf:"bytes,2,opt,name=Reserved" json:"Reserved,omitempty"`
|
Reserved *string `protobuf:"bytes,2,opt,name=Reserved" json:"Reserved,omitempty"`
|
||||||
@ -97,13 +97,13 @@ type LogGroup struct {
|
|||||||
// Reset LogGroup
|
// Reset LogGroup
|
||||||
func (m *LogGroup) Reset() { *m = LogGroup{} }
|
func (m *LogGroup) Reset() { *m = LogGroup{} }
|
||||||
|
|
||||||
// String return the compact text
|
// String returns the compact text
|
||||||
func (m *LogGroup) String() string { return proto.CompactTextString(m) }
|
func (m *LogGroup) String() string { return proto.CompactTextString(m) }
|
||||||
|
|
||||||
// ProtoMessage not implemented
|
// ProtoMessage not implemented
|
||||||
func (*LogGroup) ProtoMessage() {}
|
func (*LogGroup) ProtoMessage() {}
|
||||||
|
|
||||||
// GetLogs return the loggroup logs
|
// GetLogs returns the loggroup logs
|
||||||
func (m *LogGroup) GetLogs() []*Log {
|
func (m *LogGroup) GetLogs() []*Log {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.Logs
|
return m.Logs
|
||||||
@ -111,7 +111,8 @@ func (m *LogGroup) GetLogs() []*Log {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetReserved return Reserved
|
// GetReserved returns Reserved. An empty string is returned
|
||||||
|
// if an error occurs
|
||||||
func (m *LogGroup) GetReserved() string {
|
func (m *LogGroup) GetReserved() string {
|
||||||
if m != nil && m.Reserved != nil {
|
if m != nil && m.Reserved != nil {
|
||||||
return *m.Reserved
|
return *m.Reserved
|
||||||
@ -119,7 +120,8 @@ func (m *LogGroup) GetReserved() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTopic return Topic
|
// GetTopic returns Topic. An empty string is returned
|
||||||
|
// if an error occurs
|
||||||
func (m *LogGroup) GetTopic() string {
|
func (m *LogGroup) GetTopic() string {
|
||||||
if m != nil && m.Topic != nil {
|
if m != nil && m.Topic != nil {
|
||||||
return *m.Topic
|
return *m.Topic
|
||||||
@ -127,7 +129,8 @@ func (m *LogGroup) GetTopic() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSource return Source
|
// GetSource returns source. An empty string is returned
|
||||||
|
// if an error occurs
|
||||||
func (m *LogGroup) GetSource() string {
|
func (m *LogGroup) GetSource() string {
|
||||||
if m != nil && m.Source != nil {
|
if m != nil && m.Source != nil {
|
||||||
return *m.Source
|
return *m.Source
|
||||||
@ -135,7 +138,7 @@ func (m *LogGroup) GetSource() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// LogGroupList define the LogGroups
|
// LogGroupList defines the LogGroups
|
||||||
type LogGroupList struct {
|
type LogGroupList struct {
|
||||||
LogGroups []*LogGroup `protobuf:"bytes,1,rep,name=logGroups" json:"logGroups,omitempty"`
|
LogGroups []*LogGroup `protobuf:"bytes,1,rep,name=logGroups" json:"logGroups,omitempty"`
|
||||||
XXXUnrecognized []byte `json:"-"`
|
XXXUnrecognized []byte `json:"-"`
|
||||||
@ -144,13 +147,13 @@ type LogGroupList struct {
|
|||||||
// Reset LogGroupList
|
// Reset LogGroupList
|
||||||
func (m *LogGroupList) Reset() { *m = LogGroupList{} }
|
func (m *LogGroupList) Reset() { *m = LogGroupList{} }
|
||||||
|
|
||||||
// String return compact text
|
// String returns compact text
|
||||||
func (m *LogGroupList) String() string { return proto.CompactTextString(m) }
|
func (m *LogGroupList) String() string { return proto.CompactTextString(m) }
|
||||||
|
|
||||||
// ProtoMessage not implemented
|
// ProtoMessage not implemented
|
||||||
func (*LogGroupList) ProtoMessage() {}
|
func (*LogGroupList) ProtoMessage() {}
|
||||||
|
|
||||||
// GetLogGroups return the LogGroups
|
// GetLogGroups returns the LogGroups
|
||||||
func (m *LogGroupList) GetLogGroups() []*LogGroup {
|
func (m *LogGroupList) GetLogGroups() []*LogGroup {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.LogGroups
|
return m.LogGroups
|
||||||
@ -158,7 +161,7 @@ func (m *LogGroupList) GetLogGroups() []*LogGroup {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Marshal the logs to byte slice
|
// Marshal marshals the logs to byte slice
|
||||||
func (m *Log) Marshal() (data []byte, err error) {
|
func (m *Log) Marshal() (data []byte, err error) {
|
||||||
size := m.Size()
|
size := m.Size()
|
||||||
data = make([]byte, size)
|
data = make([]byte, size)
|
||||||
@ -353,7 +356,7 @@ func encodeVarintLog(data []byte, offset int, v uint64) int {
|
|||||||
return offset + 1
|
return offset + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size return the log's size
|
// Size returns the log's size
|
||||||
func (m *Log) Size() (n int) {
|
func (m *Log) Size() (n int) {
|
||||||
var l int
|
var l int
|
||||||
_ = l
|
_ = l
|
||||||
@ -372,7 +375,7 @@ func (m *Log) Size() (n int) {
|
|||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size return LogContent size based on Key and Value
|
// Size returns LogContent size based on Key and Value
|
||||||
func (m *LogContent) Size() (n int) {
|
func (m *LogContent) Size() (n int) {
|
||||||
var l int
|
var l int
|
||||||
_ = l
|
_ = l
|
||||||
@ -390,7 +393,7 @@ func (m *LogContent) Size() (n int) {
|
|||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size return LogGroup size based on Logs
|
// Size returns LogGroup size based on Logs
|
||||||
func (m *LogGroup) Size() (n int) {
|
func (m *LogGroup) Size() (n int) {
|
||||||
var l int
|
var l int
|
||||||
_ = l
|
_ = l
|
||||||
@ -418,7 +421,7 @@ func (m *LogGroup) Size() (n int) {
|
|||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size return LogGroupList size
|
// Size returns LogGroupList size
|
||||||
func (m *LogGroupList) Size() (n int) {
|
func (m *LogGroupList) Size() (n int) {
|
||||||
var l int
|
var l int
|
||||||
_ = l
|
_ = l
|
||||||
@ -448,7 +451,7 @@ func sozLog(x uint64) (n int) {
|
|||||||
return sovLog((x << 1) ^ (x >> 63))
|
return sovLog((x << 1) ^ (x >> 63))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unmarshal data to log
|
// Unmarshal unmarshals data to log
|
||||||
func (m *Log) Unmarshal(data []byte) error {
|
func (m *Log) Unmarshal(data []byte) error {
|
||||||
var hasFields [1]uint64
|
var hasFields [1]uint64
|
||||||
l := len(data)
|
l := len(data)
|
||||||
@ -557,7 +560,7 @@ func (m *Log) Unmarshal(data []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unmarshal data to LogContent
|
// Unmarshal unmarshals data to LogContent
|
||||||
func (m *LogContent) Unmarshal(data []byte) error {
|
func (m *LogContent) Unmarshal(data []byte) error {
|
||||||
var hasFields [1]uint64
|
var hasFields [1]uint64
|
||||||
l := len(data)
|
l := len(data)
|
||||||
@ -679,7 +682,7 @@ func (m *LogContent) Unmarshal(data []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unmarshal data to LogGroup
|
// Unmarshal unmarshals data to LogGroup
|
||||||
func (m *LogGroup) Unmarshal(data []byte) error {
|
func (m *LogGroup) Unmarshal(data []byte) error {
|
||||||
l := len(data)
|
l := len(data)
|
||||||
iNdEx := 0
|
iNdEx := 0
|
||||||
@ -853,7 +856,7 @@ func (m *LogGroup) Unmarshal(data []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unmarshal data to LogGroupList
|
// Unmarshal unmarshals data to LogGroupList
|
||||||
func (m *LogGroupList) Unmarshal(data []byte) error {
|
func (m *LogGroupList) Unmarshal(data []byte) error {
|
||||||
l := len(data)
|
l := len(data)
|
||||||
iNdEx := 0
|
iNdEx := 0
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
package alils
|
package alils
|
||||||
|
|
||||||
// InputDetail define log detail
|
// InputDetail defines log detail
|
||||||
type InputDetail struct {
|
type InputDetail struct {
|
||||||
LogType string `json:"logType"`
|
LogType string `json:"logType"`
|
||||||
LogPath string `json:"logPath"`
|
LogPath string `json:"logPath"`
|
||||||
@ -15,13 +15,13 @@ type InputDetail struct {
|
|||||||
TopicFormat string `json:"topicFormat"`
|
TopicFormat string `json:"topicFormat"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// OutputDetail define the output detail
|
// OutputDetail defines the output detail
|
||||||
type OutputDetail struct {
|
type OutputDetail struct {
|
||||||
Endpoint string `json:"endpoint"`
|
Endpoint string `json:"endpoint"`
|
||||||
LogStoreName string `json:"logstoreName"`
|
LogStoreName string `json:"logstoreName"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// LogConfig define Log Config
|
// LogConfig defines Log Config
|
||||||
type LogConfig struct {
|
type LogConfig struct {
|
||||||
Name string `json:"configName"`
|
Name string `json:"configName"`
|
||||||
InputType string `json:"inputType"`
|
InputType string `json:"inputType"`
|
||||||
|
@ -20,7 +20,7 @@ type errorMessage struct {
|
|||||||
Message string `json:"errorMessage"`
|
Message string `json:"errorMessage"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// LogProject Define the Ali Project detail
|
// LogProject defines the Ali Project detail
|
||||||
type LogProject struct {
|
type LogProject struct {
|
||||||
Name string // Project name
|
Name string // Project name
|
||||||
Endpoint string // IP or hostname of SLS endpoint
|
Endpoint string // IP or hostname of SLS endpoint
|
||||||
|
@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/gogo/protobuf/proto"
|
"github.com/gogo/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
// LogStore Store the logs
|
// LogStore stores the logs
|
||||||
type LogStore struct {
|
type LogStore struct {
|
||||||
Name string `json:"logstoreName"`
|
Name string `json:"logstoreName"`
|
||||||
TTL int
|
TTL int
|
||||||
@ -24,7 +24,7 @@ type LogStore struct {
|
|||||||
project *LogProject
|
project *LogProject
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shard define the Log Shard
|
// Shard defines the Log Shard
|
||||||
type Shard struct {
|
type Shard struct {
|
||||||
ShardID int `json:"shardID"`
|
ShardID int `json:"shardID"`
|
||||||
}
|
}
|
||||||
@ -71,7 +71,7 @@ func (s *LogStore) ListShards() (shardIDs []int, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// PutLogs put logs into logstore.
|
// PutLogs puts logs into logstore.
|
||||||
// The callers should transform user logs into LogGroup.
|
// The callers should transform user logs into LogGroup.
|
||||||
func (s *LogStore) PutLogs(lg *LogGroup) (err error) {
|
func (s *LogStore) PutLogs(lg *LogGroup) (err error) {
|
||||||
body, err := proto.Marshal(lg)
|
body, err := proto.Marshal(lg)
|
||||||
|
@ -8,13 +8,13 @@ import (
|
|||||||
"net/http/httputil"
|
"net/http/httputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MachineGroupAttribute define the Attribute
|
// MachineGroupAttribute defines the Attribute
|
||||||
type MachineGroupAttribute struct {
|
type MachineGroupAttribute struct {
|
||||||
ExternalName string `json:"externalName"`
|
ExternalName string `json:"externalName"`
|
||||||
TopicName string `json:"groupTopic"`
|
TopicName string `json:"groupTopic"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MachineGroup define the machine Group
|
// MachineGroup defines the machine Group
|
||||||
type MachineGroup struct {
|
type MachineGroup struct {
|
||||||
Name string `json:"groupName"`
|
Name string `json:"groupName"`
|
||||||
Type string `json:"groupType"`
|
Type string `json:"groupType"`
|
||||||
@ -29,20 +29,20 @@ type MachineGroup struct {
|
|||||||
project *LogProject
|
project *LogProject
|
||||||
}
|
}
|
||||||
|
|
||||||
// Machine define the Machine
|
// Machine defines the Machine
|
||||||
type Machine struct {
|
type Machine struct {
|
||||||
IP string
|
IP string
|
||||||
UniqueID string `json:"machine-uniqueid"`
|
UniqueID string `json:"machine-uniqueid"`
|
||||||
UserdefinedID string `json:"userdefined-id"`
|
UserdefinedID string `json:"userdefined-id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MachineList define the Machine List
|
// MachineList defines the Machine List
|
||||||
type MachineList struct {
|
type MachineList struct {
|
||||||
Total int
|
Total int
|
||||||
Machines []*Machine
|
Machines []*Machine
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMachines returns machine list of this machine group.
|
// ListMachines returns the machine list of this machine group.
|
||||||
func (m *MachineGroup) ListMachines() (ms []*Machine, total int, err error) {
|
func (m *MachineGroup) ListMachines() (ms []*Machine, total int, err error) {
|
||||||
h := map[string]string{
|
h := map[string]string{
|
||||||
"x-sls-bodyrawsize": "0",
|
"x-sls-bodyrawsize": "0",
|
||||||
|
@ -22,7 +22,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// connWriter implements LoggerInterface.
|
// connWriter implements LoggerInterface.
|
||||||
// it writes messages in keep-live tcp connection.
|
// Writes messages in keep-live tcp connection.
|
||||||
type connWriter struct {
|
type connWriter struct {
|
||||||
lg *logWriter
|
lg *logWriter
|
||||||
innerWriter io.WriteCloser
|
innerWriter io.WriteCloser
|
||||||
@ -33,21 +33,21 @@ type connWriter struct {
|
|||||||
Level int `json:"level"`
|
Level int `json:"level"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewConn create new ConnWrite returning as LoggerInterface.
|
// NewConn creates new ConnWrite returning as LoggerInterface.
|
||||||
func NewConn() Logger {
|
func NewConn() Logger {
|
||||||
conn := new(connWriter)
|
conn := new(connWriter)
|
||||||
conn.Level = LevelTrace
|
conn.Level = LevelTrace
|
||||||
return conn
|
return conn
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init init connection writer with json config.
|
// Init initializes a connection writer with json config.
|
||||||
// json config only need key "level".
|
// json config only needs they "level" key
|
||||||
func (c *connWriter) Init(jsonConfig string) error {
|
func (c *connWriter) Init(jsonConfig string) error {
|
||||||
return json.Unmarshal([]byte(jsonConfig), c)
|
return json.Unmarshal([]byte(jsonConfig), c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write message in connection.
|
// WriteMsg writes message in connection.
|
||||||
// if connection is down, try to re-connect.
|
// If connection is down, try to re-connect.
|
||||||
func (c *connWriter) WriteMsg(when time.Time, msg string, level int) error {
|
func (c *connWriter) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > c.Level {
|
if level > c.Level {
|
||||||
return nil
|
return nil
|
||||||
|
@ -26,7 +26,7 @@ import (
|
|||||||
// brush is a color join function
|
// brush is a color join function
|
||||||
type brush func(string) string
|
type brush func(string) string
|
||||||
|
|
||||||
// newBrush return a fix color Brush
|
// newBrush returns a fix color Brush
|
||||||
func newBrush(color string) brush {
|
func newBrush(color string) brush {
|
||||||
pre := "\033["
|
pre := "\033["
|
||||||
reset := "\033[0m"
|
reset := "\033[0m"
|
||||||
@ -53,7 +53,7 @@ type consoleWriter struct {
|
|||||||
Colorful bool `json:"color"` //this filed is useful only when system's terminal supports color
|
Colorful bool `json:"color"` //this filed is useful only when system's terminal supports color
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewConsole create ConsoleWriter returning as LoggerInterface.
|
// NewConsole creates ConsoleWriter returning as LoggerInterface.
|
||||||
func NewConsole() Logger {
|
func NewConsole() Logger {
|
||||||
cw := &consoleWriter{
|
cw := &consoleWriter{
|
||||||
lg: newLogWriter(ansicolor.NewAnsiColorWriter(os.Stdout)),
|
lg: newLogWriter(ansicolor.NewAnsiColorWriter(os.Stdout)),
|
||||||
@ -63,8 +63,8 @@ func NewConsole() Logger {
|
|||||||
return cw
|
return cw
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init init console logger.
|
// Init initianlizes the console logger.
|
||||||
// jsonConfig like '{"level":LevelTrace}'.
|
// jsonConfig must be in the format '{"level":LevelTrace}'
|
||||||
func (c *consoleWriter) Init(jsonConfig string) error {
|
func (c *consoleWriter) Init(jsonConfig string) error {
|
||||||
if len(jsonConfig) == 0 {
|
if len(jsonConfig) == 0 {
|
||||||
return nil
|
return nil
|
||||||
@ -72,7 +72,7 @@ func (c *consoleWriter) Init(jsonConfig string) error {
|
|||||||
return json.Unmarshal([]byte(jsonConfig), c)
|
return json.Unmarshal([]byte(jsonConfig), c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write message in console.
|
// WriteMsg writes message in console.
|
||||||
func (c *consoleWriter) WriteMsg(when time.Time, msg string, level int) error {
|
func (c *consoleWriter) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > c.Level {
|
if level > c.Level {
|
||||||
return nil
|
return nil
|
||||||
|
@ -15,7 +15,7 @@ import (
|
|||||||
"github.com/astaxie/beego/pkg/logs"
|
"github.com/astaxie/beego/pkg/logs"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewES return a LoggerInterface
|
// NewES returns a LoggerInterface
|
||||||
func NewES() logs.Logger {
|
func NewES() logs.Logger {
|
||||||
cw := &esLogger{
|
cw := &esLogger{
|
||||||
Level: logs.LevelDebug,
|
Level: logs.LevelDebug,
|
||||||
@ -59,7 +59,7 @@ func (el *esLogger) Init(jsonconfig string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg will write the msg and level into es
|
// WriteMsg writes the msg and level into es
|
||||||
func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
|
func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > el.Level {
|
if level > el.Level {
|
||||||
return nil
|
return nil
|
||||||
|
@ -30,7 +30,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// fileLogWriter implements LoggerInterface.
|
// fileLogWriter implements LoggerInterface.
|
||||||
// It writes messages by lines limit, file size limit, or time frequency.
|
// Writes messages by lines limit, file size limit, or time frequency.
|
||||||
type fileLogWriter struct {
|
type fileLogWriter struct {
|
||||||
sync.RWMutex // write log order by order and atomic incr maxLinesCurLines and maxSizeCurSize
|
sync.RWMutex // write log order by order and atomic incr maxLinesCurLines and maxSizeCurSize
|
||||||
// The opened file
|
// The opened file
|
||||||
@ -71,7 +71,7 @@ type fileLogWriter struct {
|
|||||||
fileNameOnly, suffix string // like "project.log", project is fileNameOnly and .log is suffix
|
fileNameOnly, suffix string // like "project.log", project is fileNameOnly and .log is suffix
|
||||||
}
|
}
|
||||||
|
|
||||||
// newFileWriter create a FileLogWriter returning as LoggerInterface.
|
// newFileWriter creates a FileLogWriter returning as LoggerInterface.
|
||||||
func newFileWriter() Logger {
|
func newFileWriter() Logger {
|
||||||
w := &fileLogWriter{
|
w := &fileLogWriter{
|
||||||
Daily: true,
|
Daily: true,
|
||||||
@ -143,7 +143,7 @@ func (w *fileLogWriter) needRotateHourly(size int, hour int) bool {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write logger message into file.
|
// WriteMsg writes logger message into file.
|
||||||
func (w *fileLogWriter) WriteMsg(when time.Time, msg string, level int) error {
|
func (w *fileLogWriter) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > w.Level {
|
if level > w.Level {
|
||||||
return nil
|
return nil
|
||||||
@ -286,7 +286,7 @@ func (w *fileLogWriter) lines() (int, error) {
|
|||||||
return count, nil
|
return count, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DoRotate means it need to write file in new file.
|
// DoRotate means it needs to write logs into a new file.
|
||||||
// new file name like xx.2013-01-01.log (daily) or xx.001.log (by line or size)
|
// new file name like xx.2013-01-01.log (daily) or xx.001.log (by line or size)
|
||||||
func (w *fileLogWriter) doRotate(logTime time.Time) error {
|
func (w *fileLogWriter) doRotate(logTime time.Time) error {
|
||||||
// file exists
|
// file exists
|
||||||
@ -397,7 +397,7 @@ func (w *fileLogWriter) Destroy() {
|
|||||||
w.fileWriter.Close()
|
w.fileWriter.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flush flush file logger.
|
// Flush flushes file logger.
|
||||||
// there are no buffering messages in file logger in memory.
|
// there are no buffering messages in file logger in memory.
|
||||||
// flush file means sync file from disk.
|
// flush file means sync file from disk.
|
||||||
func (w *fileLogWriter) Flush() {
|
func (w *fileLogWriter) Flush() {
|
||||||
|
@ -18,7 +18,7 @@ type JLWriter struct {
|
|||||||
Level int `json:"level"`
|
Level int `json:"level"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// newJLWriter create jiaoliao writer.
|
// newJLWriter creates jiaoliao writer.
|
||||||
func newJLWriter() Logger {
|
func newJLWriter() Logger {
|
||||||
return &JLWriter{Level: LevelTrace}
|
return &JLWriter{Level: LevelTrace}
|
||||||
}
|
}
|
||||||
@ -28,8 +28,8 @@ func (s *JLWriter) Init(jsonconfig string) error {
|
|||||||
return json.Unmarshal([]byte(jsonconfig), s)
|
return json.Unmarshal([]byte(jsonconfig), s)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write message in smtp writer.
|
// WriteMsg writes message in smtp writer.
|
||||||
// it will send an email with subject and only this message.
|
// Sends an email with subject and only this message.
|
||||||
func (s *JLWriter) WriteMsg(when time.Time, msg string, level int) error {
|
func (s *JLWriter) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > s.Level {
|
if level > s.Level {
|
||||||
return nil
|
return nil
|
||||||
|
@ -108,7 +108,7 @@ func Register(name string, log newLoggerFunc) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// BeeLogger is default logger in beego application.
|
// BeeLogger is default logger in beego application.
|
||||||
// it can contain several providers and log message into all providers.
|
// Can contain several providers and log message into all providers.
|
||||||
type BeeLogger struct {
|
type BeeLogger struct {
|
||||||
lock sync.Mutex
|
lock sync.Mutex
|
||||||
level int
|
level int
|
||||||
@ -140,7 +140,7 @@ type logMsg struct {
|
|||||||
var logMsgPool *sync.Pool
|
var logMsgPool *sync.Pool
|
||||||
|
|
||||||
// NewLogger returns a new BeeLogger.
|
// NewLogger returns a new BeeLogger.
|
||||||
// channelLen means the number of messages in chan(used where asynchronous is true).
|
// channelLen: the number of messages in chan(used where asynchronous is true).
|
||||||
// if the buffering chan is full, logger adapters write to file or other way.
|
// if the buffering chan is full, logger adapters write to file or other way.
|
||||||
func NewLogger(channelLens ...int64) *BeeLogger {
|
func NewLogger(channelLens ...int64) *BeeLogger {
|
||||||
bl := new(BeeLogger)
|
bl := new(BeeLogger)
|
||||||
@ -155,7 +155,7 @@ func NewLogger(channelLens ...int64) *BeeLogger {
|
|||||||
return bl
|
return bl
|
||||||
}
|
}
|
||||||
|
|
||||||
// Async set the log to asynchronous and start the goroutine
|
// Async sets the log to asynchronous and start the goroutine
|
||||||
func (bl *BeeLogger) Async(msgLen ...int64) *BeeLogger {
|
func (bl *BeeLogger) Async(msgLen ...int64) *BeeLogger {
|
||||||
bl.lock.Lock()
|
bl.lock.Lock()
|
||||||
defer bl.lock.Unlock()
|
defer bl.lock.Unlock()
|
||||||
@ -178,7 +178,7 @@ func (bl *BeeLogger) Async(msgLen ...int64) *BeeLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetLogger provides a given logger adapter into BeeLogger with config string.
|
// SetLogger provides a given logger adapter into BeeLogger with config string.
|
||||||
// config need to be correct JSON as string: {"interval":360}.
|
// config must in in JSON format like {"interval":360}}
|
||||||
func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error {
|
func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error {
|
||||||
config := append(configs, "{}")[0]
|
config := append(configs, "{}")[0]
|
||||||
for _, l := range bl.outputs {
|
for _, l := range bl.outputs {
|
||||||
@ -203,7 +203,7 @@ func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetLogger provides a given logger adapter into BeeLogger with config string.
|
// SetLogger provides a given logger adapter into BeeLogger with config string.
|
||||||
// config need to be correct JSON as string: {"interval":360}.
|
// config must in in JSON format like {"interval":360}}
|
||||||
func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error {
|
func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error {
|
||||||
bl.lock.Lock()
|
bl.lock.Lock()
|
||||||
defer bl.lock.Unlock()
|
defer bl.lock.Unlock()
|
||||||
@ -214,7 +214,7 @@ func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error {
|
|||||||
return bl.setLogger(adapterName, configs...)
|
return bl.setLogger(adapterName, configs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DelLogger remove a logger adapter in BeeLogger.
|
// DelLogger removes a logger adapter in BeeLogger.
|
||||||
func (bl *BeeLogger) DelLogger(adapterName string) error {
|
func (bl *BeeLogger) DelLogger(adapterName string) error {
|
||||||
bl.lock.Lock()
|
bl.lock.Lock()
|
||||||
defer bl.lock.Unlock()
|
defer bl.lock.Unlock()
|
||||||
@ -306,9 +306,9 @@ func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetLevel Set log message level.
|
// SetLevel sets log message level.
|
||||||
// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning),
|
// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning),
|
||||||
// log providers will not even be sent the message.
|
// log providers will not be sent the message.
|
||||||
func (bl *BeeLogger) SetLevel(l int) {
|
func (bl *BeeLogger) SetLevel(l int) {
|
||||||
bl.level = l
|
bl.level = l
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@ type SLACKWriter struct {
|
|||||||
Level int `json:"level"`
|
Level int `json:"level"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// newSLACKWriter create jiaoliao writer.
|
// newSLACKWriter creates jiaoliao writer.
|
||||||
func newSLACKWriter() Logger {
|
func newSLACKWriter() Logger {
|
||||||
return &SLACKWriter{Level: LevelTrace}
|
return &SLACKWriter{Level: LevelTrace}
|
||||||
}
|
}
|
||||||
@ -25,7 +25,7 @@ func (s *SLACKWriter) Init(jsonconfig string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write message in smtp writer.
|
// WriteMsg write message in smtp writer.
|
||||||
// it will send an email with subject and only this message.
|
// Sends an email with subject and only this message.
|
||||||
func (s *SLACKWriter) WriteMsg(when time.Time, msg string, level int) error {
|
func (s *SLACKWriter) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > s.Level {
|
if level > s.Level {
|
||||||
return nil
|
return nil
|
||||||
|
@ -35,7 +35,7 @@ type SMTPWriter struct {
|
|||||||
Level int `json:"level"`
|
Level int `json:"level"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewSMTPWriter create smtp writer.
|
// NewSMTPWriter creates the smtp writer.
|
||||||
func newSMTPWriter() Logger {
|
func newSMTPWriter() Logger {
|
||||||
return &SMTPWriter{Level: LevelTrace}
|
return &SMTPWriter{Level: LevelTrace}
|
||||||
}
|
}
|
||||||
@ -115,8 +115,8 @@ func (s *SMTPWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAd
|
|||||||
return client.Quit()
|
return client.Quit()
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteMsg write message in smtp writer.
|
// WriteMsg writes message in smtp writer.
|
||||||
// it will send an email with subject and only this message.
|
// Sends an email with subject and only this message.
|
||||||
func (s *SMTPWriter) WriteMsg(when time.Time, msg string, level int) error {
|
func (s *SMTPWriter) WriteMsg(when time.Time, msg string, level int) error {
|
||||||
if level > s.Level {
|
if level > s.Level {
|
||||||
return nil
|
return nil
|
||||||
|
Loading…
Reference in New Issue
Block a user