Как вставить значения из Postman (json type) в Postgres с помощью Gorm (go struct) - PullRequest
2 голосов
/ 13 июля 2020
• 1000 и ограничения для новой таблицы базы данных и специфические значения c, отправленные в формате json от Postman. Вы работаете с Go -Gorm?
//db file
package tiposDocumentos

import (
    "bitbucket.org/username/repositoryname/db"
    "bitbucket.org/username/repositoryname/models"
)

// Inserta un nuevo tipo de documento en la base de datos.
func InsertTipoDocumento(tp models.TiposDocumentos) (bool, error) {
    db.PsqlDb.AutoMigrate(&tp)
    if db.PsqlDb.NewRecord(tp) {
        err := db.PsqlDb.Create(&tp)
        if err != nil {
            return false, nil
        }
    } else {
        return false, errors.New("clave primaria se encuentra en uso")
    }

    return true, nil
}
package models
    
type TiposDocumentos struct {
        TdoCodigo       string  `json:"tdo_codigo" gorm:"column:tdo_codigo;type:varchar(3);PRIMARY_KEY;AUTO_INCREMENT:false"`
        TdoDescripcion  string  `json:"tdo_descripcion" gorm:"column:tdo_descripcion;type:varchar(50)"`
        TdoCodigoAfip   string  `json:"tdo_codigo_afip" gorm:"column:tdo_codigo_afip;type:varchar(10)"`
}
package routers

import (
    "bitbucket.org/username/repositoryname/db/tiposDocumentos"
    "bitbucket.org/username/repositoryname/models"
    "encoding/json"
    "fmt"
    "net/http"
)

var (
    tp models.TiposDocumentos
)

// Valida registro recibido y lo inserta en la base de datos.
func PostTiposDocuemntos(w http.ResponseWriter, r *http.Request) {
    err := json.NewDecoder(r.Body).Decode(&tp)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    estado, err := tiposDocumentos.InsertTipoDocumento(tp)
    if estado == false {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    w.WriteHeader(http.StatusCreated)
}

На этом этапе после отправки запроса от Postman программа успешно создает таблицу и ее спецификации и получает код 201, но запись не была вставлена ​​в таблицу. enter image description here View from pgAdmin4 введите описание изображения здесь

Спасибо ☻

Ошибка после успешной вставки новой записи в базу данных:

2020/07/13 12:43:28 http: panic serving 127.0.0.1:64546: runtime error: invalid memory address or nil pointer dereference
goroutine 36 [running]:
net/http.(*conn).serve.func1(0xc000230d20)
        C:/Go/src/net/http/server.go:1772 +0x140
panic(0x8085e0, 0xbb5e20)
        C:/Go/src/runtime/panic.go:975 +0x3f1
bitbucket.org/emanuelvald/gestion_personal/routers.PostTiposDocuemntos(0x912c20, 0xc00005e000, 0xc000058200)
        C:/Projects/Go/src/bitbucket.org/emanuelvald/gestion_personal/routers/tiposDocumentos.go:44 +0x151
net/http.HandlerFunc.ServeHTTP(0x893498, 0x912c20, 0xc00005e000, 0xc000058200)
        C:/Go/src/net/http/server.go:2012 +0x4b
github.com/gorilla/mux.(*Router).ServeHTTP(0xc00022a0c0, 0x912c20, 0xc00005e000, 0xc000058000)
        C:/Projects/Go/src/github.com/gorilla/mux/mux.go:210 +0xe9
net/http.serverHandler.ServeHTTP(0xc000270000, 0x912c20, 0xc00005e000, 0xc000058000)
        C:/Go/src/net/http/server.go:2807 +0xaa
net/http.(*conn).serve(0xc000230d20, 0x9137a0, 0xc000038080)
        C:/Go/src/net/http/server.go:1895 +0x873
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2933 +0x363

1 Ответ

2 голосов
/ 13 июля 2020

Рассмотрим, что происходит, когда err не равно нулю здесь:

 if err != nil {
     return false, nil
 }

, а затем вы делаете это:

estado, err := tiposDocumentos.InsertTipoDocumento(tp)
if estado == false {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}

Итак, estado ложно, а затем вы пытаетесь для доступа к err.Error(), но err равно nil, поэтому вы получите

invalid memory address or nil pointer dereference

Вероятно, вам просто нужно сделать:

 if err != nil {
     return false, err
 }

, а затем:

if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}
...