LoginSignup
15
15

More than 5 years have passed since last update.

Go言語でネットワークから取得したjsonデータを使える形にする

Last updated at Posted at 2013-05-19

GoでMicrosoft Translatorからアクセストークンを取得するまでの流れ。

Microsoft TranslatorをGoから使ってみた」から。

// アクセストークン取得時の型
type AccessTokenMessage struct {
  TokenType string `json:"token_type"`
  AccessToken string `json:"access_token"`
  ExpiresIn string `json:"expires_in"`
  Scope string `json:"scope"`
}
// アクセストークン取得時のキャッシュ型
type AccessTokenMessageCache struct {
  accessTokenMessage AccessTokenMessage
  updateTime time.Time
}

func (self *AccessTokenMessageCache) loadNewAccessTokenMessage() {
  resp, err := http.PostForm(MS_TRANSLATOR_ACCESSTOKEN_URL,
                   url.Values{
                        "client_id": {MS_TRANSLATOR_CLIENT_ID},
                        "client_secret": {MS_TRANSLATOR_CLIENT_SECRET},
                        "scope": {MS_TRANSLATOR_SCOPE},
                        "grant_type": {MS_TRANSLATOR_GRANT_TYPE}})
  if err != nil {
    panic(err)
  }
  defer resp.Body.Close()

  // thx mattn@github
  err = json.NewDecoder(resp.Body).Decode(&self.accessTokenMessage)
  if err != nil {
    panic(err)
  }

  // old
  /*
  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    panic(err)
  }

  err2 := json.Unmarshal(body, &self.accessTokenMessage)
  if err2 != nil {
    panic(err2)
  }
  */
}
15
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15