我有码头集装箱。有一个服务器(在 Go 上)处理 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 容器,在 8000 端口的 docker 容器上请求 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):
go run /home/go/hello.go
0
MMMHUHU
相关分类