add http instance function for package gins

This commit is contained in:
John Guo 2021-11-25 16:06:02 +08:00
parent be0df90d05
commit c906990b63
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,27 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gins
import (
"fmt"
"github.com/gogf/gf/v2/net/ghttp"
)
const (
frameCoreComponentNameHttpClient = "gf.core.component.httpclient"
)
// HttpClient returns an instance of http client with specified name.
func HttpClient(name ...interface{}) *ghttp.Client {
var (
instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name)
)
return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
return ghttp.NewClient()
}).(*ghttp.Client)
}

View File

@ -0,0 +1,30 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gins_test
import (
"fmt"
"testing"
"github.com/gogf/gf/v2/frame/gins"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Client(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
c = gins.HttpClient()
c1 = gins.HttpClient("c1")
c2 = gins.HttpClient("c2")
)
c.SetAgent("test1")
c.SetAgent("test2")
t.AssertNE(fmt.Sprintf(`%p`, c), fmt.Sprintf(`%p`, c1))
t.AssertNE(fmt.Sprintf(`%p`, c), fmt.Sprintf(`%p`, c2))
t.AssertNE(fmt.Sprintf(`%p`, c1), fmt.Sprintf(`%p`, c2))
})
}