9
9
"errors"
10
10
"fmt"
11
11
"net/http"
12
+ "net/url"
12
13
"strconv"
13
14
"sync"
14
15
"time"
@@ -142,15 +143,32 @@ func NewMongoDBAtlasClient(
142
143
tc := & http.Client {Transport : roundTripper }
143
144
144
145
if baseURL == "" {
145
- baseURL = "https://cloud.mongodb.com"
146
+ baseURL = mongodbatlas . CloudURL
146
147
}
147
148
148
- log .Debug ("Creating MongoDB Atlas client" ,
149
- zap .String ("baseURL" , baseURL ))
149
+ if ! isValidURL (baseURL ) {
150
+ log .Error ("Invalid baseURL provided, using default:" , zap .String ("providedURL" , baseURL ), zap .String ("defaultURL" , mongodbatlas .CloudURL ))
151
+ baseURL = mongodbatlas .CloudURL // Fallback to the default if invalid
152
+ }
150
153
151
154
client , err := mongodbatlas .New (tc , mongodbatlas .SetBaseURL (baseURL ))
152
155
if err != nil {
153
- log .Info ("failed to create client" , zap .Error (err ))
156
+ log .Error ("Failed to create client" , zap .Error (err ))
157
+ }
158
+
159
+ log .Info ("Testing MongoDB Atlas API connection" ,
160
+ zap .String ("baseURL" , baseURL ))
161
+
162
+ // Test the connection by making a simple API call (list organizations)
163
+ _ , _ , err = client .Organizations .List (context .Background (), & mongodbatlas.OrganizationsListOptions {})
164
+ if err != nil {
165
+ log .Error ("Failed to connect to MongoDB Atlas API. Possible invalid base URL or credentials:" ,
166
+ zap .String ("baseURL" , baseURL ),
167
+ zap .Error (err ), // Include the underlying error for more details
168
+ )
169
+ } else {
170
+ log .Info ("Successfully connected to MongoDB Atlas API" ,
171
+ zap .String ("baseURL" , baseURL ))
154
172
}
155
173
156
174
return & MongoDBAtlasClient {
@@ -161,6 +179,18 @@ func NewMongoDBAtlasClient(
161
179
}
162
180
}
163
181
182
+ // isValidURL checks if a string is a valid URL.
183
+ func isValidURL (str string ) bool {
184
+ u , err := url .ParseRequestURI (str )
185
+ if err != nil {
186
+ return false
187
+ }
188
+ if u .Scheme == "" || u .Host == "" {
189
+ return false
190
+ }
191
+ return true
192
+ }
193
+
164
194
func (s * MongoDBAtlasClient ) Shutdown () error {
165
195
s .transport .CloseIdleConnections ()
166
196
return s .roundTripper .Shutdown ()
0 commit comments