@@ -105,13 +105,6 @@ func (c *Config) Initialize() error {
105105 if err := c .JoinEUI .UnmarshalText ([]byte (c .joinEUI )); err != nil {
106106 return errInvalidJoinEUI .WithAttributes ("join_eui" , c .joinEUI )
107107 }
108-
109- if ! c .insecure && c .caPath != "" {
110- if err := setCustomCA (c .caPath ); err != nil {
111- return err
112- }
113- }
114-
115108 err := c .dialGRPC (
116109 grpc .FailOnNonTempDialError (true ),
117110 grpc .WithBlock (),
@@ -125,11 +118,14 @@ func (c *Config) Initialize() error {
125118}
126119
127120func (c * Config ) dialGRPC (opts ... grpc.DialOption ) error {
128- if c .insecure || c . caPath == "" {
121+ if c .insecure {
129122 opts = append (opts , grpc .WithTransportCredentials (insecure .NewCredentials ()))
130- }
131- if tls := http .DefaultTransport .(* http.Transport ).TLSClientConfig ; tls != nil {
132- opts = append (opts , grpc .WithTransportCredentials (credentials .NewTLS (tls )))
123+ } else {
124+ tlsConfig , err := generateTLSConfig (c .caPath )
125+ if err != nil {
126+ return err
127+ }
128+ opts = append (opts , grpc .WithTransportCredentials (credentials .NewTLS (tlsConfig )))
133129 }
134130
135131 ctx , cancel := context .WithTimeout (context .Background (), dialTimeout )
@@ -143,18 +139,24 @@ func (c *Config) dialGRPC(opts ...grpc.DialOption) error {
143139 return nil
144140}
145141
146- func setCustomCA (path string ) error {
147- pemBytes , err := os .ReadFile (path )
148- if err != nil {
149- return err
142+ // GenerateTLSConfig generates a TLS configuration.
143+ func generateTLSConfig (caPath string ) (cfg * tls.Config , err error ) {
144+ cfg = http .DefaultTransport .(* http.Transport ).TLSClientConfig
145+ if cfg == nil {
146+ cfg = & tls.Config {}
150147 }
151- rootCAs := http .DefaultTransport .(* http.Transport ).TLSClientConfig .RootCAs
152- if rootCAs == nil {
153- if rootCAs , err = x509 .SystemCertPool (); err != nil {
154- rootCAs = x509 .NewCertPool ()
148+ if cfg .RootCAs == nil {
149+ if cfg .RootCAs , err = x509 .SystemCertPool (); err != nil {
150+ cfg .RootCAs = x509 .NewCertPool ()
155151 }
156152 }
157- rootCAs .AppendCertsFromPEM (pemBytes )
158- http .DefaultTransport .(* http.Transport ).TLSClientConfig = & tls.Config {RootCAs : rootCAs }
159- return nil
153+ if caPath == "" {
154+ return cfg , nil
155+ }
156+ pemBytes , err := os .ReadFile (caPath )
157+ if err != nil {
158+ return nil , err
159+ }
160+ cfg .RootCAs .AppendCertsFromPEM (pemBytes )
161+ return cfg , nil
160162}
0 commit comments