我正在尝试使用Mux和GORM创建Go REST API,但是每次我尝试使用db.Create()
向表中插入新行时,它都会弹出runtime error: invalid memory address or nil pointer dereference
代码如下:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
uuid "github.com/satori/go.uuid"
)
type MetaResponse struct {
Message string `json:"message"`
Code string `json:"code"`
}
type DataResponse interface {
}
type ResponseEnvelope struct {
Meta MetaResponse `json:"meta"`
Data DataResponse `json:"data"`
}
var db *gorm.DB
type Base struct {
ID uuid.UUID `gorm:"type:uuid;primary_key;" json:"id"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}
// BeforeCreate will set a UUID rather than numeric ID.
func (base *Base) BeforeCreate(scope *gorm.Scope) error {
uuid, err := uuid.NewV4()
if err != nil {
return err
}
return scope.SetColumn("ID", uuid)
}
type Merchant struct {
Base
MerchantPhoneNumber string
MerchantActivationType int
}
func InitializeMerchantHandler(w http.ResponseWriter, r *http.Request) {
var resp ResponseEnvelope
var merchant Merchant
merchant = Merchant{
MerchantPhoneNumber: "SomeNumber",
MerchantActivationType: 1,
}
db.Create(&merchant)
resp = ResponseEnvelope{
Meta: MetaResponse{
Message: "Sukses",
Code: "2001",
},
Data: merchant,
}
json.NewEncoder(w).Encode(resp)
return
}
func main() {
db, err := gorm.Open("postgres", "host=localhost port=5432 user=postgres dbname=test password=password sslmode=disable")
if err != nil {
log.Panic(err.Error())
}
defer db.Close()
db.AutoMigrate(&Merchant{})
fmt.Println(db.DB().Ping()) // -> returns <nil>
router := mux.NewRouter().StrictSlash(true)
// Initialize Merchant Router
router.HandleFunc("/merchant/init", InitializeMerchantHandler).Methods("POST")
log.Fatal(http.ListenAndServe(":8080", router))
}
如何解决此问题?
与Mux或GORM有关吗,因为如果我使用GORM网站中的代码片段对其进行测试,则db.Create()
应该可以正常工作。
完全错误:
$ go run main.go
<nil>
2019/12/03 16:13:30 http: panic serving [::1]:58778: runtime error: invalid memory address or nil pointer dereference
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc000220000)
c:/go/src/net/http/server.go:1767 +0x140
panic(0x813d20, 0xbb85c0)
c:/go/src/runtime/panic.go:679 +0x1c0
github.com/jinzhu/gorm.(*DB).clone(0x0, 0xc0000542a0)
C:/Users/Abhishta/go/src/github.com/jinzhu/gorm/main.go:848 +0x2d
github.com/jinzhu/gorm.(*DB).NewScope(0x0, 0x83e580, 0xc0000542a0, 0x409e26)
C:/Users/Abhishta/go/src/github.com/jinzhu/gorm/main.go:201 +0x36
github.com/jinzhu/gorm.(*DB).Save(0x0, 0x83e580, 0xc0000542a0, 0xc0000542a0)
C:/Users/Abhishta/go/src/github.com/jinzhu/gorm/main.go:466 +0x4a
main.InitializeMerchantHandler(0x921920, 0xc00022c000, 0xc00021e300)
C:/Users/Abhishta/go/src/cash-it-pos-merchant-service/main.go:64 +0x130
net/http.HandlerFunc.ServeHTTP(0x8a73f0, 0x921920, 0xc00022c000, 0xc00021e300)
c:/go/src/net/http/server.go:2007 +0x4b
github.com/gorilla/mux.(*Router).ServeHTTP(0xc000200000, 0x921920, 0xc00022c000, 0xc00021e100)
C:/Users/Abhishta/go/src/github.com/gorilla/mux/mux.go:210 +0xe9
net/http.serverHandler.ServeHTTP(0xc00020e000, 0x921920, 0xc00022c000, 0xc00021e100)
c:/go/src/net/http/server.go:2802 +0xab
net/http.(*conn).serve(0xc000220000, 0x9223e0, 0xc00001a180)
c:/go/src/net/http/server.go:1890 +0x87c
created by net/http.(*Server).Serve
c:/go/src/net/http/server.go:2927 +0x395