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)
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme