From e1d340d41090de112224d86d47b873228ca5ab26 Mon Sep 17 00:00:00 2001 From: q629988171 <113960096@qq.com> Date: Wed, 30 Jun 2021 21:35:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dkey=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 修复连接默认数据库错误的问题。 2. 根据errcode存在且不为0判断为失败,否则为成功。而errmsg仅作参考,后续可能会有变动,因此不可作为是否调用成功的判据。 3. 修复判断查询数据库结果的逻辑错误。 4. 修复key缓存重复写入的问题。 --- go-wecomchan/wecomchan.go | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/go-wecomchan/wecomchan.go b/go-wecomchan/wecomchan.go index 181fc87..aae23f7 100644 --- a/go-wecomchan/wecomchan.go +++ b/go-wecomchan/wecomchan.go @@ -4,9 +4,12 @@ import ( "bytes" "context" "encoding/json" + "fmt" + "io/ioutil" "log" "net/http" + "reflect" "time" "github.com/go-redis/redis/v8" @@ -51,7 +54,7 @@ func redis_client() *redis.Client { rdb := redis.NewClient(&redis.Options{ Addr: REDIS_ADDR, Password: "", // no password set - DB: 8, // use default DB + DB: 0, // use default DB }) return rdb } @@ -92,15 +95,23 @@ func post_msg(text_msg, msg_type, post_url string) string { return string(body) } +func IsZero(v interface{}) (bool, error) { + t := reflect.TypeOf(v) + if !t.Comparable() { + return false, fmt.Errorf("type is not comparable: %v", t) + } + return v == reflect.Zero(t).Interface(), nil +} + func main() { var access_token string if redis_stat == "ON" { + log.Println("从redis获取token") rdb := redis_client() vals, err := rdb.Get(ctx, "access_token").Result() - if err != redis.Nil { - log.Println(err) + if err == redis.Nil { + log.Println("access_token does not exist") } - log.Println("从redis获取token") access_token = string(vals) } if access_token == "" { @@ -119,13 +130,19 @@ func main() { log.Println(post_status) post_response := praser_json(string(post_status)) log.Println(post_response) - if post_response["errmsg"] == "ok" && redis_stat == "ON" { - log.Println("pre to set redis key") - rdb := redis_client() - set, err := rdb.SetEX(ctx, "access_token", access_token, 7000*time.Second).Result() - log.Println(set) - if err != redis.Nil { - log.Println(err) + errcode := post_response["errcode"] + ok, err := IsZero(errcode) + if err != nil { + fmt.Printf("%v", err) + } else { + if ok && redis_stat == "ON" { + log.Println("pre to set redis key") + rdb := redis_client() + set, err := rdb.SetNX(ctx, "access_token", access_token, 7000*time.Second).Result() + log.Println(set) + if err != nil { + log.Println(err) + } } } }