将数据发布到端点后,请求正文为空

时间:2019-09-16 21:45:04

标签: go gorilla

我不确定在运行以下curl请求时为什么不发布数据:

curl --request POST http://localhost:4000 --header "Content-Type: application/json" --data '{ "hostname": "bbc.co.uk" }'

针对以下代码。它实质上只是发布带有变量hostname的json,但是由于某种原因,它没有出现在req.BodyDomain结构数组中。请注意,这是基于this tutorial

package main

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

    "github.com/gorilla/mux"
    "github.com/gorilla/handlers"
)

type Domain struct {
    hostname string   `json:"hostname,omitempty"`
}

var domains []Domain

func CreateDomainEndpoint(w http.ResponseWriter, req *http.Request) {
    var domain Domain

    fmt.Println(req.Body)
    _ = json.NewDecoder(req.Body).Decode(&domain)
    domains = append(domains, domain)
    json.NewEncoder(w).Encode(domains)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", CreateDomainEndpoint).Methods("POST")

    log.Fatal(http.ListenAndServe(":4000", handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}), handlers.AllowedOrigins([]string{"*"}))(router)))
}

1 个答案:

答案 0 :(得分:3)

  • JSON编解码器将忽略hostname字段,因为该字段不是exported。通过大写字段名称来解决。
  • domains上存在一场数据竞赛。通过使用mutex保护对变量的访问来解决。
  • 应用程序将忽略错误。通过检查并处理从JSON解码器返回的错误进行修复。

以下是带有修复程序的代码:

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "sync"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

type Domain struct {
    Hostname string `json:"hostname,omitempty"`
}

var (
    domains []Domain
    mu      sync.Mutex
)

func CreateDomainEndpoint(w http.ResponseWriter, req *http.Request) {
    var domain Domain
    if err := json.NewDecoder(req.Body).Decode(&domain); err != nil {
        http.Error(w, "bad request", 400)
        return
    }
    mu.Lock()
    domains = append(domains, domain)
    // To avoid holding the mutex while writing to the
    // response body, make a local copy of the slice header.
    d := domains
    mu.Unlock()

    json.NewEncoder(w).Encode(d)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", CreateDomainEndpoint).Methods("POST")

    log.Fatal(http.ListenAndServe(":4000", handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}), handlers.AllowedOrigins([]string{"*"}))(router)))
}