Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created March 16, 2014 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattetti/9577075 to your computer and use it in GitHub Desktop.
Save mattetti/9577075 to your computer and use it in GitHub Desktop.
func APIToken(usr, password string) (string, error) {
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
return "", fmt.Errorf("creating request")
}
req.SetBasicAuth(usr, password)
resp, err := client.Do(req)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return "", err
}
var meResp struct {
APIToken string `json:"api_token"`
Error string `json:"error"`
}
err = json.Unmarshal(body, &meResp)
if err != nil {
return "", fmt.Errorf("unmarshal response: %v", err)
}
// if there's API called failed, return the message as an error.
if meResp.Error != "" {
return "", fmt.Errorf(meResp.Error)
}
return meResp.APIToken, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment