40
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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)
}

40
33
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
40
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?