@@ -19,13 +19,17 @@ package triple
1919
2020import (
2121 "context"
22+ "crypto/tls"
23+ "crypto/x509"
24+ "io/ioutil"
2225 "reflect"
2326 "sync"
2427)
2528
2629import (
2730 "github.com/dubbogo/grpc-go"
2831 "github.com/dubbogo/grpc-go/codes"
32+ "github.com/dubbogo/grpc-go/credentials"
2933 "github.com/dubbogo/grpc-go/encoding"
3034 "github.com/dubbogo/grpc-go/encoding/hessian"
3135 "github.com/dubbogo/grpc-go/encoding/msgpack"
@@ -87,6 +91,13 @@ func NewTripleClient(impl interface{}, opt *config.Option) (*TripleClient, error
8791 )
8892 }
8993
94+ if creds , err := getClientTlsCertificate (opt ); err != nil {
95+ opt .Logger .Errorf ("TripleClient.Start: TLS config err: %v" , err )
96+ return nil , err
97+ } else if creds != nil {
98+ dialOpts = append (dialOpts , grpc .WithTransportCredentials (creds ))
99+ }
100+
90101 defaultCallOpts := make ([]grpc.CallOption , 0 )
91102 // max send/receive size
92103 if opt .GRPCMaxCallSendMsgSize != 0 {
@@ -193,3 +204,34 @@ func (t *TripleClient) Close() {
193204func (t * TripleClient ) IsAvailable () bool {
194205 return true
195206}
207+
208+ func getClientTlsCertificate (opt * config.Option ) (credentials.TransportCredentials , error ) {
209+ // no TLS
210+ if opt .TLSCertFile == "" && opt .TLSKeyFile == "" {
211+ return nil , nil
212+ }
213+
214+ if opt .CACertFile == "" {
215+ return credentials .NewClientTLSFromFile (opt .TLSCertFile , opt .TLSServerName )
216+ }
217+
218+ // need mTLS
219+ ca := x509 .NewCertPool ()
220+ caBytes , err := ioutil .ReadFile (opt .CACertFile )
221+ if err != nil {
222+ return nil , err
223+ }
224+ if ok := ca .AppendCertsFromPEM (caBytes ); ! ok {
225+ return nil , err
226+ }
227+ cert , err := tls .LoadX509KeyPair (opt .TLSCertFile , opt .TLSKeyFile )
228+ if err != nil {
229+ return nil , err
230+ }
231+
232+ return credentials .NewTLS (& tls.Config {
233+ ServerName : opt .TLSServerName ,
234+ Certificates : []tls.Certificate {cert },
235+ RootCAs : ca ,
236+ }), nil
237+ }
0 commit comments