type Token struct {
Status string `json:"status"`
Metadata struct {
Trace_id string `json:"trace_id"`
} `json:"metadata"`
Data struct {
Access_token string `json:"access_token"`
Expires_in int `json:"expires_in"`
} `json:"data"`
}
func (s *Server) getTokenFromHttp() (string, error) {
data := url.Values{}
data.Set("username", "aaa")
data.Add("password", "xxxxx")
url := "https://xxx.com/v1/user/token"
req, err := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
s.Errorf("Error: %+v\n", err)
}
body, _ := ioutil.ReadAll(resp.Body)
var b Token
if err := json.Unmarshal([]byte(body), &b); err != nil {
s.Errorf("malformat response body %v", err)
}
s.Printf("Token is %s\n", b.Data.Access_token)
return b.Data.Access_token, nil
}
func (s *Server) getTokenFromCmd() (string, error) {
cmd := exec.Command("bash", "-c", "/tmp/sclient.sh")
token, err := cmd.Output()
if err != nil {
return "", err
}
return string(token), nil
}
func (s *Server) ConsumeXX(appType string) (string, error) {
token, err := s.getTokenFromHttp()
if err != nil {
s.Errorf("Token Error: %+v\n", err)
return "", err
}
bearer := "Bearer " + token
url := "https://xxx.com/api/v1/me/resource/type/" + appType
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", bearer)
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
s.Errorf("Error: %+v\n", err)
return "", err
}
body, _ := ioutil.ReadAll(resp.Body)
return string(body), nil
}