client.go raw
1 package client
2
3 import (
4 "context"
5 "os"
6 "strings"
7
8 "github.com/ultradns/ultradns-go-sdk/internal/token"
9 "github.com/ultradns/ultradns-go-sdk/pkg/errors"
10 "golang.org/x/oauth2"
11 )
12
13 func NewClient(config Config) (client *Client, err error) {
14 client, err = validateClientConfig(&config)
15
16 if err != nil {
17 return nil, err
18 }
19
20 tokenSource := token.TokenSource{
21 BaseURL: client.baseURL,
22 Username: config.Username,
23 Password: config.Password,
24 }
25
26 client.httpClient = oauth2.NewClient(context.Background(), oauth2.ReuseTokenSource(nil, &tokenSource))
27
28 return
29 }
30
31 func validateClientConfig(config *Config) (*Client, error) {
32 config.checkEnvConfig()
33 errStr := ""
34
35 if ok := validateParameter(config.Username); !ok {
36 errStr += " username,"
37 }
38
39 if ok := validateParameter(config.Password); !ok {
40 errStr += " password,"
41 }
42
43 if ok := validateParameter(config.HostURL); !ok {
44 errStr += " host url"
45 }
46
47 if errStr != "" {
48 return nil, errors.ValidationError(strings.TrimSuffix(errStr, ","))
49 }
50
51 hostURL := strings.TrimSuffix(config.HostURL, "/")
52 client := &Client{
53 baseURL: hostURL,
54 userAgent: config.UserAgent,
55 }
56
57 return client, nil
58 }
59
60 func validateParameter(value string) bool {
61 return value != ""
62 }
63
64 func (c *Config) checkEnvConfig() {
65 if c.Username == "" {
66 c.Username = os.Getenv("ULTRADNS_USERNAME")
67 }
68
69 if c.Password == "" {
70 c.Password = os.Getenv("ULTRADNS_PASSWORD")
71 }
72
73 if c.HostURL == "" {
74 c.HostURL = os.Getenv("ULTRADNS_HOST_URL")
75 }
76 }
77