LoginSignup
15
14

More than 5 years have passed since last update.

golang JSON API クライアントサンプル

Posted at

Heroku にある JSON API へアクセスする。

  • GET で JSON を取得 [{"id":1,"name":"MotoGP"},{"id":2,"name":"Moto2"},{"id":3,"name":"Moto3"}]
  • 認証トークンを、リクエストヘッダに入れる
  • パースして、Class のスライスに格納
package main

import (
     "encoding/json"
     "fmt"
     "io/ioutil"
     "log"
     "net/http"
)

type Class struct {
     Id   int    `json:"id"`
     Name string `json:"name"`
}

func (class Class) String() string {
     return fmt.Sprintf("Id=%d Name=%s", class.Id, class.Name)
}

func main() {
     url := "https://pure-eyrie-6097.herokuapp.com/classes"

     client := &http.Client{}

     req, err := http.NewRequest("GET", url, nil)
     if err != nil {
          log.Fatal(err)
     }

     req.Header.Add("x-auth-token", "token1")
     res, err := client.Do(req)
     if err != nil {
          log.Fatal(err)
     }

     defer res.Body.Close()

     if res.StatusCode != http.StatusOK {
          log.Fatal(res)
     }

     body, err := ioutil.ReadAll(res.Body)
     if err != nil {
          log.Fatal(err)
     }

     fmt.Println(string(body))

     var classes []Class
     err = json.Unmarshal(body, &classes)
     if err != nil {
          log.Fatal(err)
     }

     for i := 0; i < len(classes); i++ {
          fmt.Println(classes[i])
     }
}
15
14
0

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
14