1
0
mirror of https://github.com/silenceper/wechat.git synced 2026-02-04 12:52:27 +08:00

实现access_token获取

This commit is contained in:
wenzl
2016-09-11 13:16:15 +08:00
parent 33f2b2ef60
commit d9075933c1
7 changed files with 195 additions and 4 deletions

11
cache/cache.go vendored Normal file
View File

@@ -0,0 +1,11 @@
package cache
import "time"
//Cache interface
type Cache interface {
Get(key string) interface{}
Set(key string, val interface{}, timeput time.Duration) error
IsExist(key string) bool
Delete(key string) error
}

51
cache/memcache.go vendored Normal file
View File

@@ -0,0 +1,51 @@
package cache
import (
"errors"
"time"
"github.com/bradfitz/gomemcache/memcache"
)
//Memcache struct contains *memcache.Client
type Memcache struct {
conn *memcache.Client
}
//NewMemcache create new memcache
func NewMemcache(server ...string) *Memcache {
mc := memcache.New(server...)
return &Memcache{mc}
}
//Get return cached value
func (mem *Memcache) Get(key string) interface{} {
if item, err := mem.conn.Get(key); err == nil {
return string(item.Value)
}
return nil
}
// IsExist check value exists in memcache.
func (mem *Memcache) IsExist(key string) bool {
_, err := mem.conn.Get(key)
if err != nil {
return false
}
return true
}
//Set cached value with key and expire time.
func (mem *Memcache) Set(key string, val interface{}, timeout time.Duration) error {
v, ok := val.(string)
if !ok {
return errors.New("val must string")
}
item := &memcache.Item{Key: key, Value: []byte(v), Expiration: int32(timeout / time.Second)}
return mem.conn.Set(item)
}
//Delete delete value in memcache.
func (mem *Memcache) Delete(key string) error {
return mem.conn.Delete(key)
}

28
cache/memcache_test.go vendored Normal file
View File

@@ -0,0 +1,28 @@
package cache
import (
"testing"
"time"
)
func TestMemcache(t *testing.T) {
mem := NewMemcache("127.0.0.1:11211")
var err error
timeoutDuration := 10 * time.Second
if err = mem.Set("username", "silenceper", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !mem.IsExist("username") {
t.Error("IsExist Error")
}
name := mem.Get("username").(string)
if name != "silenceper" {
t.Error("get Error")
}
if err = mem.Delete("username"); err != nil {
t.Errorf("delete Error , err=%v", err)
}
}