LoginSignup
33

More than 5 years have passed since last update.

Go言語: 標準パッケージのみでJSON APIクライアントを作りたい

Posted at
package main

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

type Input struct {
    Foo string `json:"foo"`
    Bar string `json:"bar"`
}

type Output struct {
    Message string `json:"message"`
}

func main() {
    // ダミーのHTTPサーバを立ち上げる
    listener, err := net.Listen("tcp", ":9999")
    if err != nil {
        return
    }
    defer listener.Close()
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        fmt.Fprint(w, `{"message": "OK"}`)
        return
    })
    go http.Serve(listener, nil)

    // jsonをデコードする
    input, err := json.Marshal(Input{Foo: "foo", Bar: "bar"})

    // HTTP リクエスト
    resp, err := http.Post("http://127.0.0.1:9999/", "application/json", bytes.NewBuffer(input))
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    // Bodyを読み込む
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    // ステータスによるエラーハンドリング
    if resp.StatusCode != http.StatusOK {
        fmt.Printf("%s", body)
        return
    }

    // BodyのJSONをデコードする
    output := Output{}
    err = json.Unmarshal(body, &output)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Printf("%#v", output)
}

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
33