AdSense

網頁

2021/12/26

Golang http handle POST JSON to struct

Go net/http handler接收POST請求的JSON並轉為struct範例。


範例環境:

  • Go 1.18


範例一 - json.Decoder

Employee為JSON要轉成的struct。若http.Request.MethodPOST時使用json.Decoder.Decode()http.Request.Body轉為struct。

main.go

package main

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

type Employee struct {
    ID   int64
    Name string
    Age  int
}

func main() {
    http.HandleFunc("/employee", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodPost:
            var emp Employee
            decoder := json.NewDecoder(r.Body)
            err := decoder.Decode(&emp) // decode JSON to Employee
            if err != nil {
                panic(err)
            }
            fmt.Println(emp)
            w.Header().Set("Content-Type", "application/json")
            json.NewEncoder(w).Encode(emp)
        default:
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }

    })

    http.ListenAndServe(":8080", nil)
}

github


範例二 - json.Unmarshal

使用ioutil.ReadAll()讀取http.Request.Bodybyte[]然後傳入json.Unmarshal()轉為struct。

main.go

package main

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

type Employee struct {
    ID   int64
    Name string
    Age  int
}

func main() {
    http.HandleFunc("/employee", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodPost:
            var emp Employee
            b, err := ioutil.ReadAll(r.Body)
            if err != nil {
                panic(err)
            }
            json.Unmarshal(b, &emp)
            fmt.Println(emp)
            w.Header().Set("Content-Type", "application/json")
            json.NewEncoder(w).Encode(emp)
        default:
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }

    })
    http.ListenAndServe(":8080", nil)
}


測試

啟動應用程式後在命令列以cURL發出以下請求。

$ curl -X POST "http://localhost:8080/employee" -H 'content-type: application/json' -d '{"id": 1, "name": "john", "age": 33}'

在console印出以下。

{1 john 33}

curl執行後返回的回應內容如下。

{"ID":1,"Name":"john","Age":33}


沒有留言:

AdSense