add redis

This commit is contained in:
Jay
2018-04-18 14:16:29 +08:00
parent 4fd4c7018e
commit 6419162471
48 changed files with 9952 additions and 14 deletions
+9 -2
View File
@@ -3,6 +3,7 @@ package context
import (
"git.trj.tw/golang/go-gallery/modules/apimsg"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// Context custom patch context
@@ -15,16 +16,22 @@ type Context struct {
type CustomMiddle func(*Context)
// PatchContext func
func PatchContext(handler CustomMiddle) gin.HandlerFunc {
func PatchContext(handler func(*Context)) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := &Context{
Context: c,
C: make(map[string]interface{}),
}
ctx.C = make(map[string]interface{})
handler(ctx)
}
}
// BindData -
func (c *Context) BindData(i interface{}) error {
b := binding.Default(c.Request.Method, c.ContentType())
return c.ShouldBindWith(i, b)
}
// NotFound response
func (c *Context) NotFound(msg interface{}) {
obj := apimsg.GetRes("NotFound", msg)
+66
View File
@@ -0,0 +1,66 @@
package memstore
import (
"errors"
"time"
"github.com/go-redis/redis"
)
var redisStore *redis.Client
// InitClient -
func InitClient() error {
redisStore = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
_, err := redisStore.Ping().Result()
return err
}
// RedisSet -
func RedisSet(namespace, key string, val string, expire int) error {
var t time.Duration
if expire > 0 {
t = time.Second * time.Duration(expire)
}
var n string
if len(namespace) > 0 {
n += namespace
n += ":"
}
if len(key) == 0 {
return errors.New("key empty")
}
n += key
err := redisStore.Set(n, val, t).Err()
return err
}
// RedisGet -
func RedisGet(namespace, key string) (string, error) {
var n string
if len(namespace) > 0 {
n += namespace
n += ":"
}
if len(key) == 0 {
return "", errors.New("key empty")
}
if len(n) > 0 {
n += ":"
}
n += key
val, err := redisStore.Get(key).Result()
return val, err
}
+14 -2
View File
@@ -1,16 +1,28 @@
package utils
import "reflect"
import (
"reflect"
"regexp"
)
// ToMap struct to map[string]interface{}
func ToMap(ss interface{}) map[string]interface{} {
t := reflect.ValueOf(ss).Elem()
smap := make(map[string]interface{})
mtag := regexp.MustCompile(`cc:\"(.+)\"`)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
smap[t.Type().Field(i).Name] = f.Interface()
tag := string(t.Type().Field(i).Tag)
str := mtag.FindStringSubmatch(tag)
name := t.Type().Field(i).Name
if len(str) > 1 {
name = str[1]
}
if name != "-" {
smap[name] = f.Interface()
}
}
return smap