如何正确处理go中由curl通过docker逐个curl传递的json数据

如何正确处理go中由curl通过docker逐个curl传递的json数据,json,docker,go,struct,Json,Docker,Go,Struct,我有码头集装箱。有一个服务器(运行中)处理8000端口上的请求。该守则: package main import ( "database/sql" _ "github.com/lib/pq" "fmt" "net/http" "encoding/json" ) type tv_type struct { brand string `json:"brand"` manufacturer string `json:"manufacture

我有码头集装箱。有一个服务器(运行中)处理8000端口上的请求。该守则:

package main

import (
    "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容器在Docker容器8000个端口上的80个自有端口代理上运行请求

然后运行以下命令:

curl -X POST -H "Content-Type:application/json" -d '{"brand":"samsung", "manufacturer":"samsung", "model":"x1", "year":2015 }' http://localhost:80
Hello WORLD
Inserting has been succesfully
但是获取的数据是错误的(nil,nil,nil,0):


代码的主要问题是,当您试图解码服务器在响应中提供的json时,您的结构无法解组数据。因为结构字段是未报告的。将结构字段更改为大写,如下所示:

type Tv_type struct { 
    Brand string `json:"brand"`
    Manufacturer string `json:"manufacturer"`
    Model string `json:"model"`
    Year int16 `json:"year"`
}
检查工作代码

Golang规范中也提到了as:

要将JSON解组到结构中,解组匹配传入对象 封送处理使用的键的键(结构字段名或其 标记),更喜欢精确匹配,但也接受不区分大小写的 匹配。默认情况下,没有相应结构的对象键 字段被忽略(有关详细信息,请参阅Decoder.disallowunknowfields) 备选方案)


首先检查
tv\u type
struct中的数据是否通过打印struct正确进入。然后检查您插入的数据是否已成功插入数据库。我已插入(“,”,“,”,0)。
type tv\u type struct{brand string
json:“brand”
manufacturer string
json:“manufacturer”
model string
year int16
json:“year”
}
Ok,那么您已经在数据库中插入了空字符串和零值。你真的想插入,那你的问题是什么。No not th struct检查您编辑的问题,在解码来自服务器的json后,我在哪里打印数据。我想插入我通过curl发送的{“brand”:“samsung”,“manufacturer”:“samsung”,“model”:“x1”,“year”:2015}
type Tv_type struct { 
    Brand string `json:"brand"`
    Manufacturer string `json:"manufacturer"`
    Model string `json:"model"`
    Year int16 `json:"year"`
}