doubi8512 2018-08-18 13:09 采纳率: 0%
浏览 155
已采纳

如何正确处理curl通过docker通过curl传递的json数据

I have docker container. There are a server(on Go) that handler post requests on 8000 port. That code:

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 container was runned that requests on 80 own port proxy on 8000 port of docker container.

And after run this:

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

But data that is getted was wrong(nil,nil,nil,0):

go run /home/go/hello.go 
   0
  • 写回答

1条回答 默认 最新

  • doushu7588 2018-08-18 13:34
    关注

    The major issue with your code is when you are trying to decode the json provided by the server in the response is your struct is unable to unmarshal the data. Since struct fields are unexported. Change the struct fields to uppercase as:

    type Tv_type struct { 
        Brand string `json:"brand"`
        Manufacturer string `json:"manufacturer"`
        Model string `json:"model"`
        Year int16 `json:"year"`
    }
    

    Check Playground example for working code.

    It is also mentioned in Golang spec for Unmarshal as:

    To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?