diff --git a/pkg/cache/conv.go b/pkg/cache/conv.go index 87800586..158f7f41 100644 --- a/pkg/cache/conv.go +++ b/pkg/cache/conv.go @@ -19,7 +19,7 @@ import ( "strconv" ) -// GetString convert interface to string. +// GetString converts interface to string. func GetString(v interface{}) string { switch result := v.(type) { case string: @@ -34,7 +34,7 @@ func GetString(v interface{}) string { return "" } -// GetInt convert interface to int. +// GetInt converts interface to int. func GetInt(v interface{}) int { switch result := v.(type) { case int: @@ -52,7 +52,7 @@ func GetInt(v interface{}) int { return 0 } -// GetInt64 convert interface to int64. +// GetInt64 converts interface to int64. func GetInt64(v interface{}) int64 { switch result := v.(type) { case int: @@ -71,7 +71,7 @@ func GetInt64(v interface{}) int64 { return 0 } -// GetFloat64 convert interface to float64. +// GetFloat64 converts interface to float64. func GetFloat64(v interface{}) float64 { switch result := v.(type) { case float64: @@ -85,7 +85,7 @@ func GetFloat64(v interface{}) float64 { return 0 } -// GetBool convert interface to bool. +// GetBool converts interface to bool. func GetBool(v interface{}) bool { switch result := v.(type) { case bool: diff --git a/pkg/cache/file.go b/pkg/cache/file.go index 6f12d3ee..dcc60bc0 100644 --- a/pkg/cache/file.go +++ b/pkg/cache/file.go @@ -30,8 +30,8 @@ import ( "time" ) -// FileCacheItem is basic unit of file cache adapter. -// it contains data and expire time. +// FileCacheItem is basic unit of file cache adapter which +// contains data and expire time. type FileCacheItem struct { Data interface{} Lastaccess time.Time @@ -54,15 +54,15 @@ type FileCache struct { EmbedExpiry int } -// NewFileCache Create new file cache with no config. -// the level and expiry need set in method StartAndGC as config string. +// NewFileCache cerates a new file cache with no config. +// The level and expiry need to be set in the method StartAndGC as config string. func NewFileCache() Cache { // return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix} return &FileCache{} } -// StartAndGC will start and begin gc for file cache. -// the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"} +// StartAndGC starts gc for file cache. +// config must be in the format {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"} func (fc *FileCache) StartAndGC(config string) error { cfg := make(map[string]string) @@ -91,14 +91,14 @@ func (fc *FileCache) StartAndGC(config string) error { return nil } -// Init will make new dir for file cache if not exist. +// Init makes new a dir for file cache if it does not already exist func (fc *FileCache) Init() { if ok, _ := exists(fc.CachePath); !ok { // todo : error handle _ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle } } -// get cached file name. it's md5 encoded. +// getCachedFilename returns an md5 encoded file name. func (fc *FileCache) getCacheFileName(key string) string { m := md5.New() io.WriteString(m, key) @@ -119,7 +119,7 @@ func (fc *FileCache) getCacheFileName(key string) string { } // Get value from file cache. -// if non-exist or expired, return empty string. +// if nonexistent or expired return an empty string. func (fc *FileCache) Get(key string) interface{} { fileData, err := FileGetContents(fc.getCacheFileName(key)) if err != nil { @@ -134,7 +134,7 @@ func (fc *FileCache) Get(key string) interface{} { } // GetMulti gets values from file cache. -// if non-exist or expired, return empty string. +// if nonexistent or expired return an empty string. func (fc *FileCache) GetMulti(keys []string) []interface{} { var rc []interface{} for _, key := range keys { @@ -144,7 +144,7 @@ func (fc *FileCache) GetMulti(keys []string) []interface{} { } // Put value into file cache. -// timeout means how long to keep this file, unit of ms. +// timeout: how long this file should be kept in ms // if timeout equals fc.EmbedExpiry(default is 0), cache this item forever. func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error { gob.Register(val) @@ -172,8 +172,8 @@ func (fc *FileCache) Delete(key string) error { return nil } -// Incr will increase cached int value. -// fc value is saving forever unless Delete. +// Incr increases cached int value. +// fc value is saved forever unless deleted. func (fc *FileCache) Incr(key string) error { data := fc.Get(key) var incr int @@ -186,7 +186,7 @@ func (fc *FileCache) Incr(key string) error { return nil } -// Decr will decrease cached int value. +// Decr decreases cached int value. func (fc *FileCache) Decr(key string) error { data := fc.Get(key) var decr int @@ -199,19 +199,18 @@ func (fc *FileCache) Decr(key string) error { return nil } -// IsExist check value is exist. +// IsExist checks if value exists. func (fc *FileCache) IsExist(key string) bool { ret, _ := exists(fc.getCacheFileName(key)) return ret } -// ClearAll will clean cached files. -// not implemented. +// ClearAll cleans cached files (not implemented) func (fc *FileCache) ClearAll() error { return nil } -// check file exist. +// Check if a file exists func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { @@ -223,19 +222,19 @@ func exists(path string) (bool, error) { return false, err } -// FileGetContents Get bytes to file. -// if non-exist, create this file. +// FileGetContents Reads bytes from a file. +// if non-existent, create this file. func FileGetContents(filename string) (data []byte, e error) { return ioutil.ReadFile(filename) } -// FilePutContents Put bytes to file. -// if non-exist, create this file. +// FilePutContents puts bytes into a file. +// if non-existent, create this file. func FilePutContents(filename string, content []byte) error { return ioutil.WriteFile(filename, content, os.ModePerm) } -// GobEncode Gob encodes file cache item. +// GobEncode Gob encodes a file cache item. func GobEncode(data interface{}) ([]byte, error) { buf := bytes.NewBuffer(nil) enc := gob.NewEncoder(buf) @@ -246,7 +245,7 @@ func GobEncode(data interface{}) ([]byte, error) { return buf.Bytes(), err } -// GobDecode Gob decodes file cache item. +// GobDecode Gob decodes a file cache item. func GobDecode(data []byte, to *FileCacheItem) error { buf := bytes.NewBuffer(data) dec := gob.NewDecoder(buf) diff --git a/pkg/cache/memory.go b/pkg/cache/memory.go index d8314e3c..792a628a 100644 --- a/pkg/cache/memory.go +++ b/pkg/cache/memory.go @@ -22,11 +22,11 @@ import ( ) var ( - // DefaultEvery means the clock time of recycling the expired cache items in memory. + // Recycle the expired cache items in memory (in seconds) DefaultEvery = 60 // 1 minute ) -// MemoryItem store memory cache item. +// MemoryItem stores memory cache item. type MemoryItem struct { val interface{} createdTime time.Time @@ -41,8 +41,8 @@ func (mi *MemoryItem) isExpire() bool { return time.Now().Sub(mi.createdTime) > mi.lifespan } -// MemoryCache is Memory cache adapter. -// it contains a RW locker for safe map storage. +// MemoryCache is a memory cache adapter. +// Contains a RW locker for safe map storage. type MemoryCache struct { sync.RWMutex dur time.Duration @@ -56,8 +56,8 @@ func NewMemoryCache() Cache { return &cache } -// Get cache from memory. -// if non-existed or expired, return nil. +// Get returns cache from memory. +// If non-existent or expired, return nil. func (bc *MemoryCache) Get(name string) interface{} { bc.RLock() defer bc.RUnlock() @@ -71,7 +71,7 @@ func (bc *MemoryCache) Get(name string) interface{} { } // GetMulti gets caches from memory. -// if non-existed or expired, return nil. +// If non-existent or expired, return nil. func (bc *MemoryCache) GetMulti(names []string) []interface{} { var rc []interface{} for _, name := range names { @@ -80,8 +80,8 @@ func (bc *MemoryCache) GetMulti(names []string) []interface{} { return rc } -// Put cache to memory. -// if lifespan is 0, it will be forever till restart. +// Put puts cache into memory. +// If lifespan is 0, it will never overwrite this value func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error { bc.Lock() defer bc.Unlock() @@ -107,8 +107,8 @@ func (bc *MemoryCache) Delete(name string) error { return nil } -// Incr increase cache counter in memory. -// it supports int,int32,int64,uint,uint32,uint64. +// Incr increases cache counter in memory. +// Supports int,int32,int64,uint,uint32,uint64. func (bc *MemoryCache) Incr(key string) error { bc.Lock() defer bc.Unlock() @@ -135,7 +135,7 @@ func (bc *MemoryCache) Incr(key string) error { return nil } -// Decr decrease counter in memory. +// Decr decreases counter in memory. func (bc *MemoryCache) Decr(key string) error { bc.Lock() defer bc.Unlock() @@ -174,7 +174,7 @@ func (bc *MemoryCache) Decr(key string) error { return nil } -// IsExist check cache exist in memory. +// IsExist checks if cache exists in memory. func (bc *MemoryCache) IsExist(name string) bool { bc.RLock() defer bc.RUnlock() @@ -184,7 +184,7 @@ func (bc *MemoryCache) IsExist(name string) bool { return false } -// ClearAll will delete all cache in memory. +// ClearAll deletes all cache in memory. func (bc *MemoryCache) ClearAll() error { bc.Lock() defer bc.Unlock() @@ -192,7 +192,7 @@ func (bc *MemoryCache) ClearAll() error { return nil } -// StartAndGC start memory cache. it will check expiration in every clock time. +// StartAndGC starts memory cache. Checks expiration in every clock time. func (bc *MemoryCache) StartAndGC(config string) error { var cf map[string]int json.Unmarshal([]byte(config), &cf) @@ -230,7 +230,7 @@ func (bc *MemoryCache) vacuum() { } } -// expiredKeys returns key list which are expired. +// expiredKeys returns keys list which are expired. func (bc *MemoryCache) expiredKeys() (keys []string) { bc.RLock() defer bc.RUnlock() @@ -242,7 +242,7 @@ func (bc *MemoryCache) expiredKeys() (keys []string) { return } -// clearItems removes all the items which key in keys. +// ClearItems removes all items who's key is in keys func (bc *MemoryCache) clearItems(keys []string) { bc.Lock() defer bc.Unlock() diff --git a/pkg/common/kv.go b/pkg/common/kv.go index 86a50132..8468f4fe 100644 --- a/pkg/common/kv.go +++ b/pkg/common/kv.go @@ -19,8 +19,8 @@ type KV interface { GetValue() interface{} } -// SimpleKV is common structure to store key-value data. -// when you need something like Pair, you can use this +// SimpleKV is common structure to store key-value pairs. +// When you need something like Pair, you can use this type SimpleKV struct { Key interface{} Value interface{} @@ -41,8 +41,8 @@ type KVs struct { kvs map[interface{}]interface{} } -// GetValueOr check whether this contains the key, -// if the key not found, the default value will be return +// GetValueOr returns the value for a given key, if non-existant +// it returns defValue func (kvs *KVs) GetValueOr(key interface{}, defValue interface{}) interface{} { v, ok := kvs.kvs[key] if ok { @@ -51,13 +51,13 @@ func (kvs *KVs) GetValueOr(key interface{}, defValue interface{}) interface{} { return defValue } -// Contains will check whether contains the key +// Contains checks if a key exists func (kvs *KVs) Contains(key interface{}) bool { _, ok := kvs.kvs[key] return ok } -// IfContains is a functional API that if the key is in KVs, the action will be invoked +// IfContains invokes the action on a key if it exists func (kvs *KVs) IfContains(key interface{}, action func(value interface{})) *KVs { v, ok := kvs.kvs[key] if ok { @@ -66,13 +66,13 @@ func (kvs *KVs) IfContains(key interface{}, action func(value interface{})) *KVs return kvs } -// Put store the value +// Put stores the value func (kvs *KVs) Put(key interface{}, value interface{}) *KVs { kvs.kvs[key] = value return kvs } -// NewKVs will create the *KVs instance +// NewKVs creates the *KVs instance func NewKVs(kvs ...KV) *KVs { res := &KVs{ kvs: make(map[interface{}]interface{}, len(kvs)), diff --git a/pkg/config/env/env.go b/pkg/config/env/env.go index 7c729780..5d8e47de 100644 --- a/pkg/config/env/env.go +++ b/pkg/config/env/env.go @@ -34,7 +34,7 @@ func init() { } } -// Get returns a value by key. +// Get returns a value for a given key. // If the key does not exist, the default value will be returned. func Get(key string, defVal string) string { if val := env.Get(key); val != nil { diff --git a/pkg/orm/cmd.go b/pkg/orm/cmd.go index 0ff4dc40..f03382e9 100644 --- a/pkg/orm/cmd.go +++ b/pkg/orm/cmd.go @@ -46,7 +46,7 @@ func printHelp(errs ...string) { os.Exit(2) } -// RunCommand listen for orm command and then run it if command arguments passed. +// RunCommand listens for orm command and runs if command arguments have been passed. func RunCommand() { if len(os.Args) < 2 || os.Args[1] != "orm" { return @@ -83,7 +83,7 @@ type commandSyncDb struct { rtOnError bool } -// parse orm command line arguments. +// Parse the orm command line arguments. func (d *commandSyncDb) Parse(args []string) { var name string @@ -96,7 +96,7 @@ func (d *commandSyncDb) Parse(args []string) { d.al = getDbAlias(name) } -// run orm line command. +// Run orm line command. func (d *commandSyncDb) Run() error { var drops []string if d.force { @@ -232,7 +232,7 @@ type commandSQLAll struct { al *alias } -// parse orm command line arguments. +// Parse orm command line arguments. func (d *commandSQLAll) Parse(args []string) { var name string @@ -243,7 +243,7 @@ func (d *commandSQLAll) Parse(args []string) { d.al = getDbAlias(name) } -// run orm line command. +// Run orm line command. func (d *commandSQLAll) Run() error { sqls, indexes := getDbCreateSQL(d.al) var all []string @@ -266,9 +266,9 @@ func init() { } // RunSyncdb run syncdb command line. -// name means table's alias name. default is "default". -// force means run next sql if the current is error. -// verbose means show all info when running command or not. +// name: Table's alias name (default is "default") +// force: Run the next sql command even if the current gave an error +// verbose: Print all information, useful for debugging func RunSyncdb(name string, force bool, verbose bool) error { BootStrap() diff --git a/pkg/plugins/apiauth/apiauth.go b/pkg/plugins/apiauth/apiauth.go index 90360aba..7b1d4405 100644 --- a/pkg/plugins/apiauth/apiauth.go +++ b/pkg/plugins/apiauth/apiauth.go @@ -65,14 +65,14 @@ import ( "sort" "time" - "github.com/astaxie/beego/pkg" + beego "github.com/astaxie/beego/pkg" "github.com/astaxie/beego/pkg/context" ) -// AppIDToAppSecret is used to get appsecret throw appid +// AppIDToAppSecret gets appsecret through appid type AppIDToAppSecret func(string) string -// APIBasicAuth use the basic appid/appkey as the AppIdToAppSecret +// APIBasicAuth uses the basic appid/appkey as the AppIdToAppSecret func APIBasicAuth(appid, appkey string) beego.FilterFunc { ft := func(aid string) string { if aid == appid { @@ -83,56 +83,58 @@ func APIBasicAuth(appid, appkey string) beego.FilterFunc { return APISecretAuth(ft, 300) } -// APIBaiscAuth calls APIBasicAuth for previous callers +// APIBasicAuth calls APIBasicAuth for previous callers func APIBaiscAuth(appid, appkey string) beego.FilterFunc { return APIBasicAuth(appid, appkey) } -// APISecretAuth use AppIdToAppSecret verify and +// APISecretAuth uses AppIdToAppSecret verify and func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc { return func(ctx *context.Context) { if ctx.Input.Query("appid") == "" { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("miss query param: appid") + ctx.WriteString("missing query parameter: appid") return } appsecret := f(ctx.Input.Query("appid")) if appsecret == "" { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("not exist this appid") + ctx.WriteString("appid query parameter missing") return } if ctx.Input.Query("signature") == "" { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("miss query param: signature") + ctx.WriteString("missing query parameter: signature") + return } if ctx.Input.Query("timestamp") == "" { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("miss query param: timestamp") + ctx.WriteString("missing query parameter: timestamp") return } u, err := time.Parse("2006-01-02 15:04:05", ctx.Input.Query("timestamp")) if err != nil { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("timestamp format is error, should 2006-01-02 15:04:05") + ctx.WriteString("incorrect timestamp format. Should be in the form 2006-01-02 15:04:05") + return } t := time.Now() if t.Sub(u).Seconds() > float64(timeout) { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("timeout! the request time is long ago, please try again") + ctx.WriteString("request timer timeout exceeded. Please try again") return } if ctx.Input.Query("signature") != Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.URL()) { ctx.ResponseWriter.WriteHeader(403) - ctx.WriteString("auth failed") + ctx.WriteString("authentication failed") } } } -// Signature used to generate signature with the appsecret/method/params/RequestURI +// Signature generates signature with appsecret/method/params/RequestURI func Signature(appsecret, method string, params url.Values, RequestURL string) (result string) { var b bytes.Buffer keys := make([]string, len(params))