1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 05:50:56 +00:00

Minor grammar fixes

This commit is contained in:
IamCathal 2020-08-05 17:44:39 +01:00
parent 3382a5baa1
commit 2f5683610f
7 changed files with 77 additions and 76 deletions

10
pkg/cache/conv.go vendored
View File

@ -19,7 +19,7 @@ import (
"strconv" "strconv"
) )
// GetString convert interface to string. // GetString converts interface to string.
func GetString(v interface{}) string { func GetString(v interface{}) string {
switch result := v.(type) { switch result := v.(type) {
case string: case string:
@ -34,7 +34,7 @@ func GetString(v interface{}) string {
return "" return ""
} }
// GetInt convert interface to int. // GetInt converts interface to int.
func GetInt(v interface{}) int { func GetInt(v interface{}) int {
switch result := v.(type) { switch result := v.(type) {
case int: case int:
@ -52,7 +52,7 @@ func GetInt(v interface{}) int {
return 0 return 0
} }
// GetInt64 convert interface to int64. // GetInt64 converts interface to int64.
func GetInt64(v interface{}) int64 { func GetInt64(v interface{}) int64 {
switch result := v.(type) { switch result := v.(type) {
case int: case int:
@ -71,7 +71,7 @@ func GetInt64(v interface{}) int64 {
return 0 return 0
} }
// GetFloat64 convert interface to float64. // GetFloat64 converts interface to float64.
func GetFloat64(v interface{}) float64 { func GetFloat64(v interface{}) float64 {
switch result := v.(type) { switch result := v.(type) {
case float64: case float64:
@ -85,7 +85,7 @@ func GetFloat64(v interface{}) float64 {
return 0 return 0
} }
// GetBool convert interface to bool. // GetBool converts interface to bool.
func GetBool(v interface{}) bool { func GetBool(v interface{}) bool {
switch result := v.(type) { switch result := v.(type) {
case bool: case bool:

47
pkg/cache/file.go vendored
View File

@ -30,8 +30,8 @@ import (
"time" "time"
) )
// FileCacheItem is basic unit of file cache adapter. // FileCacheItem is basic unit of file cache adapter which
// it contains data and expire time. // contains data and expire time.
type FileCacheItem struct { type FileCacheItem struct {
Data interface{} Data interface{}
Lastaccess time.Time Lastaccess time.Time
@ -54,15 +54,15 @@ type FileCache struct {
EmbedExpiry int EmbedExpiry int
} }
// NewFileCache Create new file cache with no config. // NewFileCache cerates a new file cache with no config.
// the level and expiry need set in 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}
return &FileCache{} return &FileCache{}
} }
// StartAndGC will start and begin gc for file cache. // StartAndGC starts gc for file cache.
// the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"} // config must be in the format {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}
func (fc *FileCache) StartAndGC(config string) error { func (fc *FileCache) StartAndGC(config string) error {
cfg := make(map[string]string) cfg := make(map[string]string)
@ -91,14 +91,14 @@ func (fc *FileCache) StartAndGC(config string) error {
return nil 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() { func (fc *FileCache) Init() {
if ok, _ := exists(fc.CachePath); !ok { // todo : error handle if ok, _ := exists(fc.CachePath); !ok { // todo : error handle
_ = os.MkdirAll(fc.CachePath, os.ModePerm) // 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 { func (fc *FileCache) getCacheFileName(key string) string {
m := md5.New() m := md5.New()
io.WriteString(m, key) io.WriteString(m, key)
@ -119,7 +119,7 @@ func (fc *FileCache) getCacheFileName(key string) string {
} }
// Get value from file cache. // 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{} { func (fc *FileCache) Get(key string) interface{} {
fileData, err := FileGetContents(fc.getCacheFileName(key)) fileData, err := FileGetContents(fc.getCacheFileName(key))
if err != nil { if err != nil {
@ -134,7 +134,7 @@ func (fc *FileCache) Get(key string) interface{} {
} }
// GetMulti gets values from file cache. // 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{} { func (fc *FileCache) GetMulti(keys []string) []interface{} {
var rc []interface{} var rc []interface{}
for _, key := range keys { for _, key := range keys {
@ -144,7 +144,7 @@ func (fc *FileCache) GetMulti(keys []string) []interface{} {
} }
// Put value into file cache. // 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. // if timeout equals fc.EmbedExpiry(default is 0), cache this item forever.
func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error { func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error {
gob.Register(val) gob.Register(val)
@ -172,8 +172,8 @@ func (fc *FileCache) Delete(key string) error {
return nil return nil
} }
// Incr will increase cached int value. // Incr increases cached int value.
// fc value is saving forever unless Delete. // fc value is saved forever unless deleted.
func (fc *FileCache) Incr(key string) error { func (fc *FileCache) Incr(key string) error {
data := fc.Get(key) data := fc.Get(key)
var incr int var incr int
@ -186,7 +186,7 @@ func (fc *FileCache) Incr(key string) error {
return nil return nil
} }
// Decr will decrease cached int value. // Decr decreases cached int value.
func (fc *FileCache) Decr(key string) error { func (fc *FileCache) Decr(key string) error {
data := fc.Get(key) data := fc.Get(key)
var decr int var decr int
@ -199,19 +199,18 @@ func (fc *FileCache) Decr(key string) error {
return nil return nil
} }
// IsExist check value is exist. // IsExist checks if value exists.
func (fc *FileCache) IsExist(key string) bool { func (fc *FileCache) IsExist(key string) bool {
ret, _ := exists(fc.getCacheFileName(key)) ret, _ := exists(fc.getCacheFileName(key))
return ret return ret
} }
// ClearAll will clean cached files. // ClearAll cleans cached files (not implemented)
// not implemented.
func (fc *FileCache) ClearAll() error { func (fc *FileCache) ClearAll() error {
return nil return nil
} }
// check file exist. // Check if a file exists
func exists(path string) (bool, error) { func exists(path string) (bool, error) {
_, err := os.Stat(path) _, err := os.Stat(path)
if err == nil { if err == nil {
@ -223,19 +222,19 @@ func exists(path string) (bool, error) {
return false, err return false, err
} }
// FileGetContents Get bytes to file. // FileGetContents Reads bytes from a file.
// if non-exist, create this file. // if non-existent, create this file.
func FileGetContents(filename string) (data []byte, e error) { func FileGetContents(filename string) (data []byte, e error) {
return ioutil.ReadFile(filename) return ioutil.ReadFile(filename)
} }
// FilePutContents Put bytes to file. // FilePutContents puts bytes into a file.
// if non-exist, create this file. // if non-existent, create this file.
func FilePutContents(filename string, content []byte) error { func FilePutContents(filename string, content []byte) error {
return ioutil.WriteFile(filename, content, os.ModePerm) 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) { func GobEncode(data interface{}) ([]byte, error) {
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buf) enc := gob.NewEncoder(buf)
@ -246,7 +245,7 @@ func GobEncode(data interface{}) ([]byte, error) {
return buf.Bytes(), err return buf.Bytes(), err
} }
// GobDecode Gob decodes file cache item. // GobDecode Gob decodes a file cache item.
func GobDecode(data []byte, to *FileCacheItem) error { func GobDecode(data []byte, to *FileCacheItem) error {
buf := bytes.NewBuffer(data) buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf) dec := gob.NewDecoder(buf)

34
pkg/cache/memory.go vendored
View File

@ -22,11 +22,11 @@ import (
) )
var ( 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 DefaultEvery = 60 // 1 minute
) )
// MemoryItem store memory cache item. // MemoryItem stores memory cache item.
type MemoryItem struct { type MemoryItem struct {
val interface{} val interface{}
createdTime time.Time createdTime time.Time
@ -41,8 +41,8 @@ func (mi *MemoryItem) isExpire() bool {
return time.Now().Sub(mi.createdTime) > mi.lifespan return time.Now().Sub(mi.createdTime) > mi.lifespan
} }
// MemoryCache is Memory cache adapter. // MemoryCache is a memory cache adapter.
// it contains a RW locker for safe map storage. // Contains a RW locker for safe map storage.
type MemoryCache struct { type MemoryCache struct {
sync.RWMutex sync.RWMutex
dur time.Duration dur time.Duration
@ -56,8 +56,8 @@ func NewMemoryCache() Cache {
return &cache return &cache
} }
// Get cache from memory. // Get returns cache from memory.
// if non-existed or expired, return nil. // If non-existent or expired, return nil.
func (bc *MemoryCache) Get(name string) interface{} { func (bc *MemoryCache) Get(name string) interface{} {
bc.RLock() bc.RLock()
defer bc.RUnlock() defer bc.RUnlock()
@ -71,7 +71,7 @@ func (bc *MemoryCache) Get(name string) interface{} {
} }
// GetMulti gets caches from memory. // 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{} { func (bc *MemoryCache) GetMulti(names []string) []interface{} {
var rc []interface{} var rc []interface{}
for _, name := range names { for _, name := range names {
@ -80,8 +80,8 @@ func (bc *MemoryCache) GetMulti(names []string) []interface{} {
return rc return rc
} }
// Put cache to memory. // Put puts cache into memory.
// if lifespan is 0, it will be forever till restart. // If lifespan is 0, it will never overwrite this value
func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error { func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error {
bc.Lock() bc.Lock()
defer bc.Unlock() defer bc.Unlock()
@ -107,8 +107,8 @@ func (bc *MemoryCache) Delete(name string) error {
return nil return nil
} }
// Incr increase cache counter in memory. // Incr increases cache counter in memory.
// it supports int,int32,int64,uint,uint32,uint64. // Supports int,int32,int64,uint,uint32,uint64.
func (bc *MemoryCache) Incr(key string) error { func (bc *MemoryCache) Incr(key string) error {
bc.Lock() bc.Lock()
defer bc.Unlock() defer bc.Unlock()
@ -135,7 +135,7 @@ func (bc *MemoryCache) Incr(key string) error {
return nil return nil
} }
// Decr decrease counter in memory. // Decr decreases counter in memory.
func (bc *MemoryCache) Decr(key string) error { func (bc *MemoryCache) Decr(key string) error {
bc.Lock() bc.Lock()
defer bc.Unlock() defer bc.Unlock()
@ -174,7 +174,7 @@ func (bc *MemoryCache) Decr(key string) error {
return nil return nil
} }
// IsExist check cache exist in memory. // IsExist checks if cache exists in memory.
func (bc *MemoryCache) IsExist(name string) bool { func (bc *MemoryCache) IsExist(name string) bool {
bc.RLock() bc.RLock()
defer bc.RUnlock() defer bc.RUnlock()
@ -184,7 +184,7 @@ func (bc *MemoryCache) IsExist(name string) bool {
return false return false
} }
// ClearAll will delete all cache in memory. // ClearAll deletes all cache in memory.
func (bc *MemoryCache) ClearAll() error { func (bc *MemoryCache) ClearAll() error {
bc.Lock() bc.Lock()
defer bc.Unlock() defer bc.Unlock()
@ -192,7 +192,7 @@ func (bc *MemoryCache) ClearAll() error {
return nil 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 { func (bc *MemoryCache) StartAndGC(config string) error {
var cf map[string]int var cf map[string]int
json.Unmarshal([]byte(config), &cf) 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) { func (bc *MemoryCache) expiredKeys() (keys []string) {
bc.RLock() bc.RLock()
defer bc.RUnlock() defer bc.RUnlock()
@ -242,7 +242,7 @@ func (bc *MemoryCache) expiredKeys() (keys []string) {
return 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) { func (bc *MemoryCache) clearItems(keys []string) {
bc.Lock() bc.Lock()
defer bc.Unlock() defer bc.Unlock()

View File

@ -19,8 +19,8 @@ type KV interface {
GetValue() interface{} GetValue() interface{}
} }
// SimpleKV is common structure to store key-value data. // SimpleKV is common structure to store key-value pairs.
// when you need something like Pair, you can use this // When you need something like Pair, you can use this
type SimpleKV struct { type SimpleKV struct {
Key interface{} Key interface{}
Value interface{} Value interface{}
@ -41,8 +41,8 @@ type KVs struct {
kvs map[interface{}]interface{} kvs map[interface{}]interface{}
} }
// GetValueOr check whether this contains the key, // GetValueOr returns the value for a given key, if non-existant
// if the key not found, the default value will be return // it returns defValue
func (kvs *KVs) GetValueOr(key interface{}, defValue interface{}) interface{} { func (kvs *KVs) GetValueOr(key interface{}, defValue interface{}) interface{} {
v, ok := kvs.kvs[key] v, ok := kvs.kvs[key]
if ok { if ok {
@ -51,13 +51,13 @@ func (kvs *KVs) GetValueOr(key interface{}, defValue interface{}) interface{} {
return defValue return defValue
} }
// Contains will check whether contains the key // Contains checks if a key exists
func (kvs *KVs) Contains(key interface{}) bool { func (kvs *KVs) Contains(key interface{}) bool {
_, ok := kvs.kvs[key] _, ok := kvs.kvs[key]
return ok 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 { func (kvs *KVs) IfContains(key interface{}, action func(value interface{})) *KVs {
v, ok := kvs.kvs[key] v, ok := kvs.kvs[key]
if ok { if ok {
@ -66,13 +66,13 @@ func (kvs *KVs) IfContains(key interface{}, action func(value interface{})) *KVs
return kvs return kvs
} }
// Put store the value // Put stores the value
func (kvs *KVs) Put(key interface{}, value interface{}) *KVs { func (kvs *KVs) Put(key interface{}, value interface{}) *KVs {
kvs.kvs[key] = value kvs.kvs[key] = value
return kvs return kvs
} }
// NewKVs will create the *KVs instance // NewKVs creates the *KVs instance
func NewKVs(kvs ...KV) *KVs { func NewKVs(kvs ...KV) *KVs {
res := &KVs{ res := &KVs{
kvs: make(map[interface{}]interface{}, len(kvs)), kvs: make(map[interface{}]interface{}, len(kvs)),

View File

@ -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. // If the key does not exist, the default value will be returned.
func Get(key string, defVal string) string { func Get(key string, defVal string) string {
if val := env.Get(key); val != nil { if val := env.Get(key); val != nil {

View File

@ -46,7 +46,7 @@ func printHelp(errs ...string) {
os.Exit(2) 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() { func RunCommand() {
if len(os.Args) < 2 || os.Args[1] != "orm" { if len(os.Args) < 2 || os.Args[1] != "orm" {
return return
@ -83,7 +83,7 @@ type commandSyncDb struct {
rtOnError bool rtOnError bool
} }
// parse orm command line arguments. // Parse the orm command line arguments.
func (d *commandSyncDb) Parse(args []string) { func (d *commandSyncDb) Parse(args []string) {
var name string var name string
@ -96,7 +96,7 @@ func (d *commandSyncDb) Parse(args []string) {
d.al = getDbAlias(name) d.al = getDbAlias(name)
} }
// run orm line command. // Run orm line command.
func (d *commandSyncDb) Run() error { func (d *commandSyncDb) Run() error {
var drops []string var drops []string
if d.force { if d.force {
@ -232,7 +232,7 @@ type commandSQLAll struct {
al *alias al *alias
} }
// parse orm command line arguments. // Parse orm command line arguments.
func (d *commandSQLAll) Parse(args []string) { func (d *commandSQLAll) Parse(args []string) {
var name string var name string
@ -243,7 +243,7 @@ func (d *commandSQLAll) Parse(args []string) {
d.al = getDbAlias(name) d.al = getDbAlias(name)
} }
// run orm line command. // Run orm line command.
func (d *commandSQLAll) Run() error { func (d *commandSQLAll) Run() error {
sqls, indexes := getDbCreateSQL(d.al) sqls, indexes := getDbCreateSQL(d.al)
var all []string var all []string
@ -266,9 +266,9 @@ func init() {
} }
// RunSyncdb run syncdb command line. // RunSyncdb run syncdb command line.
// name means table's alias name. default is "default". // name: Table's alias name (default is "default")
// force means run next sql if the current is error. // force: Run the next sql command even if the current gave an error
// verbose means show all info when running command or not. // verbose: Print all information, useful for debugging
func RunSyncdb(name string, force bool, verbose bool) error { func RunSyncdb(name string, force bool, verbose bool) error {
BootStrap() BootStrap()

View File

@ -65,14 +65,14 @@ import (
"sort" "sort"
"time" "time"
"github.com/astaxie/beego/pkg" beego "github.com/astaxie/beego/pkg"
"github.com/astaxie/beego/pkg/context" "github.com/astaxie/beego/pkg/context"
) )
// AppIDToAppSecret is used to get appsecret throw appid // AppIDToAppSecret gets appsecret through appid
type AppIDToAppSecret func(string) string 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 { func APIBasicAuth(appid, appkey string) beego.FilterFunc {
ft := func(aid string) string { ft := func(aid string) string {
if aid == appid { if aid == appid {
@ -83,56 +83,58 @@ func APIBasicAuth(appid, appkey string) beego.FilterFunc {
return APISecretAuth(ft, 300) return APISecretAuth(ft, 300)
} }
// APIBaiscAuth calls APIBasicAuth for previous callers // APIBasicAuth calls APIBasicAuth for previous callers
func APIBaiscAuth(appid, appkey string) beego.FilterFunc { func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
return APIBasicAuth(appid, appkey) return APIBasicAuth(appid, appkey)
} }
// APISecretAuth use AppIdToAppSecret verify and // APISecretAuth uses AppIdToAppSecret verify and
func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc { func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc {
return func(ctx *context.Context) { return func(ctx *context.Context) {
if ctx.Input.Query("appid") == "" { if ctx.Input.Query("appid") == "" {
ctx.ResponseWriter.WriteHeader(403) ctx.ResponseWriter.WriteHeader(403)
ctx.WriteString("miss query param: appid") ctx.WriteString("missing query parameter: appid")
return return
} }
appsecret := f(ctx.Input.Query("appid")) appsecret := f(ctx.Input.Query("appid"))
if appsecret == "" { if appsecret == "" {
ctx.ResponseWriter.WriteHeader(403) ctx.ResponseWriter.WriteHeader(403)
ctx.WriteString("not exist this appid") ctx.WriteString("appid query parameter missing")
return return
} }
if ctx.Input.Query("signature") == "" { if ctx.Input.Query("signature") == "" {
ctx.ResponseWriter.WriteHeader(403) ctx.ResponseWriter.WriteHeader(403)
ctx.WriteString("miss query param: signature") ctx.WriteString("missing query parameter: signature")
return return
} }
if ctx.Input.Query("timestamp") == "" { if ctx.Input.Query("timestamp") == "" {
ctx.ResponseWriter.WriteHeader(403) ctx.ResponseWriter.WriteHeader(403)
ctx.WriteString("miss query param: timestamp") ctx.WriteString("missing query parameter: timestamp")
return return
} }
u, err := time.Parse("2006-01-02 15:04:05", ctx.Input.Query("timestamp")) u, err := time.Parse("2006-01-02 15:04:05", ctx.Input.Query("timestamp"))
if err != nil { if err != nil {
ctx.ResponseWriter.WriteHeader(403) 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 return
} }
t := time.Now() t := time.Now()
if t.Sub(u).Seconds() > float64(timeout) { if t.Sub(u).Seconds() > float64(timeout) {
ctx.ResponseWriter.WriteHeader(403) 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 return
} }
if ctx.Input.Query("signature") != if ctx.Input.Query("signature") !=
Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.URL()) { Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.URL()) {
ctx.ResponseWriter.WriteHeader(403) 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) { func Signature(appsecret, method string, params url.Values, RequestURL string) (result string) {
var b bytes.Buffer var b bytes.Buffer
keys := make([]string, len(params)) keys := make([]string, len(params))