-
Notifications
You must be signed in to change notification settings - Fork 0
/
getToken.go
72 lines (55 loc) · 1.76 KB
/
getToken.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
63
64
65
66
67
68
69
70
71
72
/*
ESRI REST API implementation library.
GetToken function.
reference:
https://developers.arcgis.com/rest/services-reference/enterprise/generate-token.htm
portal: https://geo.int.geomsf.org/portal/sharing/rest/generateToken
*/
package go_esri
import (
"encoding/json"
"errors"
"net/url"
"github.com/go-resty/resty/v2"
)
// JSON fields in response from getToken request
type token struct {
Token string `json:"token"`
Expires string `json:"expires"`
}
// Queries an ESRI server to obtain an authentication token, returns this token as a string.
func GetToken(username, password, serverName string) (string, error) {
// ----------------------------------------- build and validate url
baseUrl, err := url.Parse(serverName)
if err != nil {
return "", err
}
baseUrl.Path += "/admin/generateToken" // portal: sharing/rest/generateToken
// ----------------------------------------- build url encode string to be included in the header body
v := url.Values{}
v.Set("username", username)
v.Add("password", password)
v.Add("client", "requestip")
v.Add("f", "json")
// ----------------------------------------- request the token
req := resty.New()
// to debug use: req.SetDebug(true).R().
resp, err := req.R().
SetHeader("Content-type", "application/x-www-form-urlencoded").
SetBody(string(v.Encode())). // convert url encoding to string first
Post(baseUrl.String())
if err != nil {
return "", err
}
// ----------------------------------------- decode json response and return token
var obj token
err = json.Unmarshal(resp.Body(), &obj)
if err != nil {
return "", err
}
// empty token, something went wrong, return body which contains ESRI error message
if obj.Token == "" {
return "", errors.New(string(resp.Body()))
}
return obj.Token, nil
}