LoginSignup
23
23

More than 3 years have passed since last update.

Golangで構造体をJSONに変換してPOSTする

Last updated at Posted at 2019-06-17

ポイントまとめ

Golangで構造体をJSONに変換してからPOSTするまでの流れのメモ
ポイントは以下の通り
1. JSONに変換できるように構造体を定義
2. Content-Typeをapplication/jsonに指定
3. JSONをbytes.Buffer型に変換して送信

サンプルコード

package main

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

// test server
const URL = "http://localhost:8000" 

// sample structure
//// ポイント1
type Sample struct {
    Id   int    `json: "id"`
    Name string `json: "name"`
}

func main() {
    // build sample structure
    sample := new(Sample)
    sample.Id = 0
    sample.Name = "hoge"

    // encode json
    sample_json, _ := json.Marshal(sample)
    fmt.Printf("[+] %s\n", string(sample_json))

    // send json
    //// ポイント2, 3
    res, err := http.Post(URL, "application/json", bytes.NewBuffer(sample_json))
    defer res.Body.Close()

    if err != nil {
        fmt.Println("[!] " + err.Error())
    } else {
        fmt.Println("[*] " + res.Status)
    }
}

❯ nc -l 8000
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Go-http-client/1.1
Content-Length: 22
Content-Type: application/json
Accept-Encoding: gzip

{"Id":0,"Name":"hoge"}
23
23
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
23
23