gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:17 25 4
gpt4 key购买 nike

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

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

针对下面的代码。它本质上只是发布带有变量 hostname 的 json,但出于某种原因,它没有出现在 req.Body 中,也没有出现在 Domain 结构数组中。请注意这是基于 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)))
}

最佳答案

  • JSON 编解码器忽略 hostname 字段,因为该字段不是 exported .通过将字段名称大写来修复。
  • 上存在数据竞争。通过使用 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)))
}

关于go - 将数据发布到端点后请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57964787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com