53
35

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形式のrequestを受ける

Posted at

json形式でpostされたhttp requestを処理するサンプル。
今回はpostするjsonのデータ構造を特に決めていないのでパース結果をmap[string]interface{}に保存。

srv.go
package main

import (
  "net/http"
  "io"
  "encoding/json"
  "fmt"
  "strconv"
)

func dumpJsonRequestHandlerFunc(w http.ResponseWriter, req *http.Request){
  //Validate request
  if req.Method != "POST" {
    w.WriteHeader(http.StatusBadRequest)
    return
  }

  if req.Header.Get("Content-Type") != "application/json" {
    w.WriteHeader(http.StatusBadRequest)
    return
  }

  //To allocate slice for request body
  length, err := strconv.Atoi(req.Header.Get("Content-Length"))
  if err != nil {
    w.WriteHeader(http.StatusInternalServerError)
    return
  }
  
  //Read body data to parse json
  body := make([]byte, length)
  length, err = req.Body.Read(body)
  if err != nil && err != io.EOF {
    w.WriteHeader(http.StatusInternalServerError)
    return
  }
  
  //parse json
  var jsonBody map[string]interface{}
  err = json.Unmarshal(body[:length], &jsonBody)
  if err != nil {
    w.WriteHeader(http.StatusInternalServerError)
    return
  }
  fmt.Printf("%v\n", jsonBody)
  
  w.WriteHeader(http.StatusOK)  
}

func main(){
  http.HandleFunc("/json", dumpJsonRequestHandlerFunc)
  http.ListenAndServe(":8080", nil)
}

json形式のリクエストを受けるサーバを立ち上げる

$go run srv.go

json形式のリクエストをcurlで叩く

$curl -v -H "Content-Type: application/json" -X POST -d '{"integer":1,"string":"xyz", "object": { "element": 1 } , "array": [1, 2, 3]}' http://localhost:8080/json
53
35
2

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
53
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?