Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.
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)
}

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした