Hey Guys,
when I want insert into db I got an error.
my method for insert:
func RegisterUser(db *sql.DB, w http.ResponseWriter, r *http.Request) {
user := model.User{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
respondError(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
sqlStatement := `
INSERT INTO users (id, name, avatar, mobile, birth_day, identify, cart, credit, type, password)
VALUES ($1, $2, $3, $4, $5, &6, &7, &8, &9)
RETURNING id`
stmt, err := db.Prepare(sqlStatement)
fmt.Println("******************here2", user)
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
var userID int
if err := stmt.QueryRow(sqlStatement, user.ID, user.Name, user.Avatar, user.Mobile, user.BirthDay, user.Identify, user.Cart, user.Credit, user.Type, user.Password); err != nil {
//respondError(w, http.StatusInternalServerError, err.Error())
log.Fatal(err)
return
}
fmt.Println("New record ID is:", userID)
respondJSON(w, http.StatusCreated, user)
}
and this is error log:
http: panic serving [::1]:39878: runtime error: invalid memory address or nil pointer dereference
goroutine 18 [running]:
more explain:
I have User struct with this field:
type User struct {
Base
Name string `json:"name"`
Avatar string `json:"avatar"`
Email string `db:"unique;not null";json:"email"`
Mobile string `json:"mobile"`
BirthDay string `json:"birthday"`
Identify string `json:"identify"`
Cart string `json:"cart"`
Credit string `json:"credit"`
Type int `json:"type"`
Password string `json:"password"`
Permissions string
}
and my Base in User struct is:
import (
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
)
type Base struct {
ID uuid.UUID `db:"type:uuid;primary_key;not null;" json:"-"`
}
func (base *Base) BeforeCreate(scope *gorm.Scope) error {
uuid, err := uuid.NewV4()
if err != nil {
return err
}
return scope.SetColumn("ID", uuid)
}
and that Base is to make UUID for every User record.
but I got an error in this part:
stmt, err := db.Prepare(sqlStatement)
fmt.Println("******************here2", user)
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
may please help me to fix this section for insert data into database?