dty98339 2019-09-16 21:45
浏览 42
已采纳

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

I'm not sure why the data being posted is not present when running the following curl request:

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

against the code below. It's essentially just posting json with the variable hostname but for some reason it's not appearing in req.Body or appearing in the Domain structure array. Please note this is based on 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条回答 默认 最新

  • doupuchao4256 2019-09-16 23:07
    关注
    • The JSON codec ignores the hostname field because the field is not exported. Fix by capitalizing the name of the field.
    • There is a data race on domains. Fix by protecting access to the variable with a mutex.
    • The application ignores errors. Fix by checking for and handing the error returned from the JSON decoder.

    Here's the code with fixes:

    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)))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端