Go http handler寫出JSON回應的方式如下。
範例
使用http.ResponseWriter.Header().Set()
設定回應的Content-Type為application/json
。
呼叫json.NewEncoder()
傳入ResponseWriter
物件取得json.Encoder
,其會將encode結果透過傳入的writer寫出。
接著調用json.Encoder.Encode()
傳入struct轉為JSON並寫到輸出串流。
main.go
package main
import (
"encoding/json"
"net/http"
)
type Employee struct {
Id int
Name string
Age int
}
func main() {
http.HandleFunc("/employee", func(rw http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
emp := Employee{
Id: 1,
Name: "john",
Age: 33,
}
rw.Header().Set("Content-Type", "application/json")
json.NewEncoder(rw).Encode(emp) // use ReponseWriter with encoder to write json encoding of emp to stream.
default:
http.Error(rw, "Method not allowed", http.StatusMethodNotAllowed)
}
})
http.ListenAndServe(":8080", nil)
}
測試
啟動應用程式後在命令列以cURL執行curl -v "http://localhost:8080/employee"
。
$ curl -v "http://localhost:8080/employee"
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /employee HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Thu, 28 Apr 2022 15:02:42 GMT
< Content-Length: 32
<
{"Id":1,"Name":"john","Age":33}
從上可看到回應的Content-Type為application/json
;回應內容為{"Id":1,"Name":"john","Age":33}
。
沒有留言:
張貼留言