0
我試圖將一個json請求(用大猩猩/多路複用器處理)解碼到一個結構中,並將其與GORM一起保存到mysql數據庫中。我用curl發送請求(參見cURL命令)。該請求無效,並應在2點失敗1)它不應該解碼到結構2)它不應該保存到數據庫。我不知道我做錯了,並希望幫助:)Golang GORM並將HTTP.Request.Body解碼爲JSON
解碼的結構是這樣的:
{{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }
cURL命令:
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8080/api/dimoengra/subscribe
代碼:
package subscribe
import "github.com/jinzhu/gorm"
import "net/http"
import "encoding/json"
import "fmt"
// Subscription ...
type Subscription struct {
gorm.Model
ServiceID string `gorm:"not null" json:"ServiceID"`
MessageCode string `gorm:"not null" json:"MessageCode"`
SubscriberCallbackURL string `gorm:"not null" json:"SubscriberCallbackURL"`
}
// SubscribeHandler ...
func SubscribeHandler(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
fmt.Println("Handle Subscribtion")
if r.Body == nil {
http.Error(w, "Please send a request body", 400)
fmt.Println("Empty body")
return
}
var s Subscription
err := json.NewDecoder(r.Body).Decode(&s)
if err != nil {
fmt.Println("Error:", err)
http.Error(w, err.Error(), 400)
return
}
fmt.Println(s)
err = Subscribe(db, s)
if err != nil {
fmt.Println("Error:", err)
http.Error(w, err.Error(), 400)
return
}
}
// Subscribe ...
func Subscribe(db *gorm.DB, subscription Subscription) error {
err := db.Create(&subscription)
fmt.Println("err:", err.Error)
return err.Error
}