Przeglądaj źródła

InitHTTPClients 换到 MchMgr 中,这样在初始化可以报错

yaotian 8 lat temu
rodzic
commit
9ab9df6e80
2 zmienionych plików z 31 dodań i 24 usunięć
  1. 7 24
      wechat.go
  2. 24 0
      wxcontext/context.go

+ 7 - 24
wechat.go

@@ -3,16 +3,14 @@ package gowechat
 
 import (
 	"fmt"
-	"net/http"
 	"sync"
 
 	"github.com/astaxie/beego/cache"
-	"github.com/yaotian/gowechat/util"
 	"github.com/yaotian/gowechat/wxcontext"
 )
 
-//MemCache if wxcontext.Config no cache, this will give a default memory cache.
-var MemCache cache.Cache
+//memCache if wxcontext.Config no cache, this will give a default memory cache.
+var memCache cache.Cache
 
 // Wechat struct
 type Wechat struct {
@@ -28,33 +26,16 @@ func NewWechat(cfg wxcontext.Config) *Wechat {
 
 func initContext(cfg *wxcontext.Config, context *wxcontext.Context) {
 	if cfg.Cache == nil {
-		if MemCache == nil {
-			MemCache, _ = cache.NewCache("memory", `{"interval":60}`)
+		if memCache == nil {
+			memCache, _ = cache.NewCache("memory", `{"interval":60}`)
 		}
-		cfg.Cache = MemCache
+		cfg.Cache = memCache
 	}
 	context.Config = cfg
 
 	context.SetAccessTokenLock(new(sync.RWMutex))
 	context.SetJsAPITicketLock(new(sync.RWMutex))
 
-	//create http client
-	if cfg.SslCertFilePath != "" && cfg.SslKeyFilePath != "" {
-		if client, err := util.NewTLSHttpClient(cfg.SslCertFilePath, cfg.SslKeyFilePath); err == nil {
-			context.SHTTPClient = client
-		} else {
-			fmt.Print(err)
-		}
-	}
-
-	if cfg.SslCertContent != "" && cfg.SslKeyContent != "" {
-		if client, err := util.NewTLSHttpClientFromContent(cfg.SslCertContent, cfg.SslKeyContent); err == nil {
-			context.SHTTPClient = client
-		} else {
-			fmt.Print(err)
-		}
-	}
-	context.HTTPClient = http.DefaultClient
 }
 
 //MchMgr 商户平台
@@ -110,5 +91,7 @@ func (wc *Wechat) checkCfgMch() (err error) {
 	if wc.Context.SslKeyFilePath == "" && wc.Context.SslKeyContent == "" {
 		return fmt.Errorf("%s", "配置中没有SslKey")
 	}
+	//初始化 http client, 有错误会出错误
+	err = wc.Context.InitHTTPClients()
 	return
 }

+ 24 - 0
wxcontext/context.go

@@ -3,6 +3,8 @@ package wxcontext
 import (
 	"net/http"
 	"sync"
+
+	"github.com/yaotian/gowechat/util"
 )
 
 // Context struct
@@ -46,3 +48,25 @@ func (ctx *Context) SetJsAPITicketLock(lock *sync.RWMutex) {
 func (ctx *Context) GetJsAPITicketLock() *sync.RWMutex {
 	return ctx.jsAPITicketLock
 }
+
+//InitHTTPClients Context中初始化 httpclient httpsclient
+func (ctx *Context) InitHTTPClients() (err error) {
+	//create http client
+	if ctx.SslCertFilePath != "" && ctx.SslKeyFilePath != "" {
+		if client, err := util.NewTLSHttpClient(ctx.SslCertFilePath, ctx.SslKeyFilePath); err == nil {
+			ctx.SHTTPClient = client
+		} else {
+			return err
+		}
+	}
+
+	if ctx.SslCertContent != "" && ctx.SslKeyContent != "" {
+		if client, err := util.NewTLSHttpClientFromContent(ctx.SslCertContent, ctx.SslKeyContent); err == nil {
+			ctx.SHTTPClient = client
+		} else {
+			return err
+		}
+	}
+	ctx.HTTPClient = http.DefaultClient
+	return
+}