Hello,
Still new-ish to golang but im trying to send a curl to an auth/login endpoint for an API and retrieve back a token. This is what I have so far:
func FetchToken() string {
client := &http.Client{}
var data = strings.NewReader(`grant_type=&username=<username>&password=<password>&scope=&client_id=&client_secret=`)
req, err := http.NewRequest("POST", "<url>", data)
if err != nil {
panic(err)
}
req.Header.Set("accept", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return string(bodyText)
}
The expected output is something like:
{
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "<token>",
"ExpiresIn": 3600,
"TokenType": "Bearer",
"ResponseMetadata": {
"RequestId": "<id>",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"date": "Wed, 22 Nov 2023 19:02:22 GMT",
"content-type": "application/x-amz-json-1.1",
"content-length": "4294",
"connection": "keep-alive",
"x-amzn-requestid": "<id>"
},
"RetryAttempts": 0
}
}
When I get a successful payload back with the token, how do I need to change my function code to basically do this:
token := FetchToken()
fmt.printf("%v", token.AuthenticationResult.AccessToken)