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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)