/
app.go
76 lines (63 loc) · 1.83 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package sdk
import (
"crypto/tls"
"crypto/x509"
"errors"
"net/http"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/bianjieai/opb-sdk-go/pkg/app/sdk/client"
"github.com/bianjieai/opb-sdk-go/pkg/app/sdk/model"
"github.com/irisnet/core-sdk-go/types"
)
// NewClient create a new IRITA OPB client
func NewClient(cfg types.ClientConfig, authToken *model.AuthToken) client.Client {
httpHeader := http.Header{}
if authToken != nil {
if authToken.GetEnableTLS() {
certificateList, err := getGateWayTlsCertPool(cfg.RPCAddr)
if err != nil {
panic(err)
}
roots := x509.NewCertPool()
for i := range certificateList {
roots.AddCert(certificateList[i])
}
cert := credentials.NewTLS(&tls.Config{ServerName: authToken.GetDomain(), RootCAs: roots, InsecureSkipVerify: true})
// overwrite grpcOpts
grpcOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(authToken),
grpc.WithTransportCredentials(cert),
}
cfg.GRPCOptions = grpcOpts
} else {
// overwrite grpcOpts
grpcOpts := []grpc.DialOption{
grpc.WithInsecure(),
grpc.WithPerRPCCredentials(authToken),
}
cfg.GRPCOptions = grpcOpts
}
if projectKey := authToken.GetProjectKey(); projectKey != "" {
httpHeader.Set("x-api-key", authToken.GetProjectKey())
}
}
cfg.Header = httpHeader
return client.NewClient(cfg)
}
func getGateWayTlsCertPool(gateWayUrl string) ([]*x509.Certificate, error) {
if !strings.Contains(strings.ToLower(gateWayUrl), "https://") {
return nil, errors.New("tls is enabled, but the address is http")
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(gateWayUrl)
defer resp.Body.Close()
if err != nil {
return nil, err
}
return resp.TLS.PeerCertificates, nil
}