Debian Codegraph @

dnsimple/dnsimple.go

raw
1 // Package dnsimple implements a client for the DNSimple API.
2 //
3 // In order to use this package you will need a DNSimple account and your API Token.
4 package dnsimple
5
6 import (
7 "bytes"
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http"
12 "time"
13 )
14
15 const (
16 libraryVersion = "0.1"
17 baseURL = "https://api.dnsimple.com/"
18 userAgent = "dnsimple-go/" + libraryVersion
19
20 apiVersion = "v1"
21 )
22
23 type Client struct {
24 // HTTP client used to communicate with the API.
25 HttpClient *http.Client
26
27 // Credentials used for accessing the DNSimple API
28 Credentials Credentials
29
30 // Base URL for API requests.
31 // Defaults to the public DNSimple API, but can be set to a different endpoint (e.g. the sandbox).
32 // BaseURL should always be specified with a trailing slash.
33 BaseURL string
34
35 // User agent used when communicating with the DNSimple API.
36 UserAgent string
37
38 // Services used for talking to different parts of the DNSimple API.
39 Contacts *ContactsService
40 Domains *DomainsService
41 Registrar *RegistrarService
42 Users *UsersService
43 }
44
45 // NewClient returns a new DNSimple API client.
46 func NewClient(apiToken, email string) *Client {
47 return NewAuthenticatedClient(NewApiTokenCredentials(email, apiToken))
48
49 }
50
51 // NewAuthenticatedClient returns a new DNSimple API client using the given
52 // credentials.
53 func NewAuthenticatedClient(credentials Credentials) *Client {
54 c := &Client{Credentials: credentials, HttpClient: &http.Client{}, BaseURL: baseURL, UserAgent: userAgent}
55 c.Contacts = &ContactsService{client: c}
56 c.Domains = &DomainsService{client: c}
57 c.Registrar = &RegistrarService{client: c}
58 c.Users = &UsersService{client: c}
59 return c
60 }
61
62 // NewRequest creates an API request.
63 // The path is expected to be a relative path and will be resolved
64 // according to the BaseURL of the Client. Paths should always be specified without a preceding slash.
65 func (client *Client) NewRequest(method, path string, payload interface{}) (*http.Request, error) {
66 url := client.BaseURL + fmt.Sprintf("%s/%s", apiVersion, path)
67
68 body := new(bytes.Buffer)
69 if payload != nil {
70 err := json.NewEncoder(body).Encode(payload)
71 if err != nil {
72 return nil, err
73 }
74 }
75
76 req, err := http.NewRequest(method, url, body)
77 if err != nil {
78 return nil, err
79 }
80
81 req.Header.Set("Content-Type", "application/json")
82 req.Header.Add("Accept", "application/json")
83 req.Header.Add("User-Agent", client.UserAgent)
84 req.Header.Add(client.Credentials.HttpHeader())
85
86 return req, nil
87 }
88
89 func (c *Client) get(path string, v interface{}) (*Response, error) {
90 return c.Do("GET", path, nil, v)
91 }
92
93 func (c *Client) post(path string, payload, v interface{}) (*Response, error) {
94 return c.Do("POST", path, payload, v)
95 }
96
97 func (c *Client) put(path string, payload, v interface{}) (*Response, error) {
98 return c.Do("PUT", path, payload, v)
99 }
100
101 func (c *Client) delete(path string, payload interface{}) (*Response, error) {
102 return c.Do("DELETE", path, payload, nil)
103 }
104
105 // Do sends an API request and returns the API response.
106 // The API response is JSON decoded and stored in the value pointed by v,
107 // or returned as an error if an API error has occurred.
108 // If v implements the io.Writer interface, the raw response body will be written to v,
109 // without attempting to decode it.
110 func (c *Client) Do(method, path string, payload, v interface{}) (*Response, error) {
111 req, err := c.NewRequest(method, path, payload)
112 if err != nil {
113 return nil, err
114 }
115
116 res, err := c.HttpClient.Do(req)
117 if err != nil {
118 return nil, err
119 }
120 defer res.Body.Close()
121
122 response := &Response{Response: res}
123
124 err = CheckResponse(res)
125 if err != nil {
126 return response, err
127 }
128
129 if v != nil {
130 if w, ok := v.(io.Writer); ok {
131 io.Copy(w, res.Body)
132 } else {
133 err = json.NewDecoder(res.Body).Decode(v)
134 }
135 }
136
137 return response, err
138 }
139
140 // A Response represents an API response.
141 type Response struct {
142 *http.Response
143 }
144
145 // An ErrorResponse represents an error caused by an API request.
146 type ErrorResponse struct {
147 Response *http.Response // HTTP response that caused this error
148 Message string `json:"message"` // human-readable message
149 }
150
151 // Error implements the error interface.
152 func (r *ErrorResponse) Error() string {
153 return fmt.Sprintf("%v %v: %d %v",
154 r.Response.Request.Method, r.Response.Request.URL,
155 r.Response.StatusCode, r.Message)
156 }
157
158 // CheckResponse checks the API response for errors, and returns them if present.
159 // A response is considered an error if the status code is different than 2xx. Specific requests
160 // may have additional requirements, but this is sufficient in most of the cases.
161 func CheckResponse(r *http.Response) error {
162 if code := r.StatusCode; 200 <= code && code <= 299 {
163 return nil
164 }
165
166 errorResponse := &ErrorResponse{Response: r}
167 err := json.NewDecoder(r.Body).Decode(errorResponse)
168 if err != nil {
169 return err
170 }
171
172 return errorResponse
173 }
174
175 // Date custom type.
176 type Date struct {
177 time.Time
178 }
179
180 // UnmarshalJSON handles the deserialization of the custom Date type.
181 func (d *Date) UnmarshalJSON(data []byte) error {
182 var s string
183 if err := json.Unmarshal(data, &s); err != nil {
184 return fmt.Errorf("date should be a string, got %s", data)
185 }
186 t, err := time.Parse("2006-01-02", s)
187 if err != nil {
188 return fmt.Errorf("invalid date: %v", err)
189 }
190 d.Time = t
191 return nil
192 }