Last active
October 7, 2016 23:33
-
-
Save IndianGuru/dfc62e7c6bdbb3a2ce6d0956d593ed6d to your computer and use it in GitHub Desktop.
Go program to access Clarifai API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"net/url" | |
"strings" | |
) | |
const ( | |
clientID = "Your ClientID" | |
clientSecret = "Your ClientSecret" | |
) | |
type TokenResp struct { | |
AccessToken string `json:"access_token"` | |
ExpiresIn int `json:"expires_in"` | |
Scope string `json:"scope"` | |
TokenType string `json:"token_type"` | |
} | |
func main() { | |
accessToken, err := requestAccessToken() | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("AccessToken = ", accessToken) | |
} | |
func requestAccessToken() (string, error) { | |
form := url.Values{} | |
form.Set("grant_type", "client_credentials") | |
form.Set("client_id", clientID) | |
form.Set("client_secret", clientSecret) | |
formData := strings.NewReader(form.Encode()) | |
url := fmt.Sprintf("https://api.clarifai.com/v1/token/") | |
req, err := http.NewRequest("POST", url, formData) | |
if err != nil { | |
return "", err | |
} | |
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | |
httpClient := &http.Client{} | |
resp, err := httpClient.Do(req) | |
if err != nil { | |
return "", err | |
} | |
defer resp.Body.Close() | |
var record TokenResp | |
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil { | |
return "", err | |
} | |
return record.AccessToken, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment