This repository has been archived by the owner on Oct 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
62 lines (53 loc) · 1.71 KB
/
request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package sdk
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type HTTPMethod string
const (
Get HTTPMethod = "GET"
Post HTTPMethod = "POST"
Put HTTPMethod = "PUT"
Delete HTTPMethod = "DELETE"
)
// Used internally in order to act as a middleware to add authentication to a requested URI
func (c *Connection) prepareRequest(path string, method HTTPMethod, body interface{}) (*http.Request, error) {
// Creates a local copy of the smarthome base URL, then sets the path
u := c.SmarthomeURL
u.Path = path
// If the authentication mode is set to `AuthMethodQueryPassword`, encode username and password and attach it to the URL
if c.authMethod == AuthMethodQueryPassword {
query := u.Query()
query.Set("username", c.credStore.Username)
query.Set("password", c.credStore.Password)
u.RawQuery = query.Encode()
} else if c.authMethod == AuthMethodQueryToken {
query := u.Query()
query.Set("token", c.credStore.Token)
u.RawQuery = query.Encode()
}
// If a body is specified, encode it to JSON
encodedBody := make([]byte, 0)
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
encodedBody = b
}
// Creates the request
r, err := http.NewRequest(string(method), u.String(), bytes.NewBuffer(encodedBody))
if err != nil {
return nil, err
}
// If the authentication mode is set to `AuthMethodCookiePassword` or `AuthMethodCookieToken`, add the cookie to the request
if c.authMethod == AuthMethodCookiePassword || c.authMethod == AuthMethodCookieToken {
r.AddCookie(c.sessionCookie)
}
// Set `Content-Type` and `User-Agent`
r.Header.Set("Content-Type", "application/json")
r.Header.Set("User-Agent", fmt.Sprintf("SmarthomeSDK/%s", Version))
return r, nil
}