我有碼頭集裝箱。有一個服務器(在 Go 上)處理 8000 端口上的發布請求。該代碼:package mainimport ( "database/sql" _ "github.com/lib/pq" "fmt" "net/http" "encoding/json")type tv_type struct { brand string `json:"brand"` manufacturer string `json:"manufacturer"` model string `json:"model"` year int16 `json:"year"`} func handler(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { //blahblah } fmt.Fprintln(w, "Hello WORLD") if r.Method == http.MethodPost { connStr := "user=www password=qwerty dbname=products sslmode=disable" db, err := sql.Open("postgres", connStr) defer db.Close() if err != nil { panic(err) } decoder := json.NewDecoder(r.Body) var t tv_type err = decoder.Decode(&t) if err != nil { panic(err) } _, err = db.Exec("insert into TV (brand, manufacturer, model, year) values ($1, $2, $3, $4)", t.brand, t.manufacturer, t.model, t.year) if err != nil { panic(err) } else { fmt.Println(t.brand, t.manufacturer, t.model, t.year) fmt.Fprintln(w, "Inserting has been succesfully") } }}func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8000", nil)}運行 Docker 容器,在 8000 端口的 docker 容器上請求 80 自己的端口代理。運行這個之后:curl -X POST -H "Content-Type:application/json" -d '{"brand":"samsung", "manufacturer":"samsung", "model":"x1", "year":2015 }' http://localhost:80Hello WORLDInserting has been succesfully但是得到的數據是錯誤的(nil,nil,nil,0):go run /home/go/hello.go 0
如何正確處理通過curl通過docker傳遞的go中的json數據
慕碼人8056858
2023-03-21 15:42:45