发布数据到端点后的请求体为空
时间:2024-03-06
浏览:152
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《发布数据到端点后的请求体为空》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我不确定为什么在运行以下curl请求时不存在正在发布的数据:
curl --request post http://localhost:4000 --header "content-type: application/json" --data '{ "hostname": "bbc.co.uk" }'
针对下面的代码。它本质上只是使用变量 hostname 发布 json,但由于某种原因,它没有出现在 req.body 中或出现在 domain 结构数组中。请注意,这是基于本教程的
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。请通过将字段名称大写来修复。 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)))
}今天关于《发布数据到端点后的请求体为空》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
