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
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).