LoginSignup
13
10

More than 5 years have passed since last update.

goでjson apiを叩く

Last updated at Posted at 2016-04-27

goでjson apiを叩くサンプル(Decoderを使ったバージョンも追加)

json_sample.go
package main

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

type JsonTestDate struct {
  Time string `json:"time"`
  Msec int64  `json:"milliseconds_since_epoch"`
  Date string `json:"date"`
}

func main(){
  useDecoder := false
  flag.BoolVar(&useDecoder, "decoder", false, "use json decoder")
  flag.Parse()

  res, err := http.Get("http://date.jsontest.com/")
  if err != nil {
    log.Fatal(err)
  }
  defer res.Body.Close()
  if res.StatusCode != 200 {
    fmt.Println("StatusCode=%d", res.StatusCode)
    return
  }
  //Dump response status line
  fmt.Printf("======Status line======\n")
  fmt.Printf("%s %s\n", res.Proto, res.Status)

  //Dump response header
  fmt.Printf("======Header======\n")
  for k, v := range res.Header {
    fmt.Printf("%s:%s\n", k, v)    
  }

  var d JsonTestDate
  if !useDecoder {
    //Dump response body (use json.Unmarshal)
    fmt.Printf("======Body (use json.Unmarshal)======\n")
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
      log.Fatal(err)    
    }

    err = json.Unmarshal(body, &d)
    if err != nil {
      log.Fatal(err)    
    }
  } else {
    //Dump response body (use Decoder)
    fmt.Printf("======Body(use json.Decoder)======\n")
    decoder := json.NewDecoder(res.Body)
    err = decoder.Decode(&d)
    if err != nil {
      log.Fatal(err)    
    }
  }
  fmt.Printf("%v\n", d)
}

➜  golan go run json_sample.go -decoder=1
======Status line======
HTTP/1.1 200 OK
======Header======
Access-Control-Allow-Origin:[*]
Content-Type:[application/json; charset=ISO-8859-1]
Date:[Fri, 10 Jun 2016 14:28:38 GMT]
Server:[Google Frontend]
Content-Length:[100]
======Body(use json.Decoder)======
{02:28:38 PM 1465568918612 06-10-2016}
➜  golan go run json_sample.go
======Status line======
HTTP/1.1 200 OK
======Header======
Access-Control-Allow-Origin:[*]
Content-Type:[application/json; charset=ISO-8859-1]
Date:[Fri, 10 Jun 2016 14:28:43 GMT]
Server:[Google Frontend]
Content-Length:[100]
======Body (use json.Unmarshal)======
{02:28:43 PM 1465568923974 06-10-2016}
13
10
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
13
10