尝试使用Fiber和GORM编写一个创建数据库的POST请求,但是出现了错误。

huangapple go评论89阅读模式
英文:

Trying to write a post request to create a database with fiber and gorm and it gives me an error

问题

尝试使用gorm作为数据库和fiber作为golang框架来输出一个POST请求,但似乎有时候不起作用,有时候返回"json: unmarshal(non-pointer, main.AcctDetails)"的错误。请有人帮我解决这个问题,我已经卡在这里很长时间了。

package main

import (
    "github.com/gofiber/fiber/v2"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

var (
    DB  *gorm.DB
    err error
)

type AcctDetails struct {
    gorm.Model
    ID           uint   `json:"id"`
    AcctName     string `json:"acctname"`
    AcctNumber   string `json:"acctnumber"`
    UsersPhoneNo string `json:"usersphoneno"`
}

func Routers(app *fiber.App) {
    app.Post("/bank", CreateUser)
}

func CreateUser(c *fiber.Ctx) error {
    info := new(AcctDetails)

    if err := c.BodyParser(info); err != nil {
        return c.Status(500).SendString(err.Error())
    }

    DB.Create(&info)
    return c.Status(200).JSON(&info)
}

func main() {
    app := fiber.New()
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("Cannot Connect To Database")
    }
    DB = db
    DB.AutoMigrate(&AcctDetails{})
    Routers(app)
    app.Listen(":3000")
}

它返回以下错误:

PS C:\Users\Chinonso\Desktop\New folder\GO\main> go run main.go

2022/04/29 22:47:51 C:/Users/Chinonso/Desktop/New folder/GO/main/main.go:45 SLOW SQL >= 200ms
[272.120ms] [rows:0] CREATE TABLE `acct_details` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`acct_name` text,`acct_number` text,`users_phone_no` text,PRIMARY KEY (`id`))

*this is after the server starts*

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x7ff7bc6f05a2]

goroutine 8 [running]:
gorm.io/gorm.(*DB).Create(0xc0000c0000, {0x7ff7bc92e820, 0xc0000b4010})
        C:/Users/Chinonso/go/pkg/mod/gorm.io/gorm@v1.23.5/finisher_api.go:18 +0x22
main.CreateUser(0xc0000c0000)
        C:/Users/Chinonso/Desktop/New folder/GO/main/main.go:35 +0xe5
github.com/gofiber/fiber/v2.(*App).next(0xc0000023c0, 0xc0000c0000)
        C:/Users/Chinonso/go/pkg/mod/github.com/gofiber/fiber/v2@v2.32.0/router.go:132 +0x1be
github.com/gofiber/fiber/v2.(*App).handler(0xc0000023c0, 0x7ff7bc3a19b7)
        C:/Users/Chinonso/go/pkg/mod/github.com/gofiber/fiber/v2@v2.32.0/router.go:159 +0x45
github.com/valyala/fasthttp.(*Server).serveConn(0xc000127440, {0x7ff7bca94f30, 0xc000006ef8})
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/server.go:2338 +0x11ae
github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc0002a9360, 0xc0002bd440)
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/workerpool.go:224 +0xa9
github.com/valyala/fasthttp.(*workerPool).getCh.func1()
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/workerpool.go:196 +0x38
created by github.com/valyala/fasthttp.(*workerPool).getCh
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/workerpool.go:195 +0x1b5
exit status 2
PS C:\Users\Chinonso\Desktop\New folder\GO\main>

请有人帮我解决这段代码,这个问题困扰了我两个月了。

英文:

trying to oupt a post (create) request using gorm as my database and fiber as my golang framewor but it seems like it is not working sometimes it returns "json: unmarshal(non-pointer, main.AcctDetails)" someone should please help me out i have been stuck here for quite a long time

package main

import (

    "github.com/gofiber/fiber/v2"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var (
	DB	*gorm.DB
	err error
)

type AcctDetails struct {
		gorm.Model
		ID           uint	 `json:"id"`
		AcctName     string	 `json:"acctname"`
		AcctNumber   string	 `json:"acctnumber"`
		UsersPhoneNo string	 `json:"usersphoneno"`
	}


func Routers(app *fiber.App) {
	app.Post("/bank", CreateUser)
}

func CreateUser(c *fiber.Ctx) error {
	info := new(AcctDetails)
	
	if err := c.BodyParser(info); err != nil {
		return c.Status(500).SendString(err.Error())
	}

	DB.Create(&info)
	return c.Status(200).JSON(&info)
}

func main() {
	app := fiber.New()
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("Cannot Connect To Database")
	}
	db.AutoMigrate(&AcctDetails{})
	Routers(app)
	app.Listen(":3000")
}

and it returns this as error

PS C:\Users\Chinonso\Desktop\New folder\GO\main> go run main.go

2022/04/29 22:47:51 C:/Users/Chinonso/Desktop/New folder/GO/main/main.go:45 SLOW SQL >= 200ms
[272.120ms] [rows:0] CREATE TABLE `acct_details` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`acct_name` text,`acct_number` text,`users_phone_no` text,PRIMARY KEY (`id`))

*this is after the server starts*

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x7ff7bc6f05a2]

goroutine 8 [running]:
gorm.io/gorm.(*DB).Create(0xc0000c0000, {0x7ff7bc92e820, 0xc0000b4010})
        C:/Users/Chinonso/go/pkg/mod/gorm.io/gorm@v1.23.5/finisher_api.go:18 +0x22
main.CreateUser(0xc0000c0000)
        C:/Users/Chinonso/Desktop/New folder/GO/main/main.go:35 +0xe5
github.com/gofiber/fiber/v2.(*App).next(0xc0000023c0, 0xc0000c0000)
        C:/Users/Chinonso/go/pkg/mod/github.com/gofiber/fiber/v2@v2.32.0/router.go:132 +0x1be
github.com/gofiber/fiber/v2.(*App).handler(0xc0000023c0, 0x7ff7bc3a19b7)
        C:/Users/Chinonso/go/pkg/mod/github.com/gofiber/fiber/v2@v2.32.0/router.go:159 +0x45
github.com/valyala/fasthttp.(*Server).serveConn(0xc000127440, {0x7ff7bca94f30, 0xc000006ef8})
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/server.go:2338 +0x11ae
github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc0002a9360, 0xc0002bd440)
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/workerpool.go:224 +0xa9
github.com/valyala/fasthttp.(*workerPool).getCh.func1()
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/workerpool.go:196 +0x38
created by github.com/valyala/fasthttp.(*workerPool).getCh
        C:/Users/Chinonso/go/pkg/mod/github.com/valyala/fasthttp@v1.35.0/workerpool.go:195 +0x1b5
exit status 2
PS C:\Users\Chinonso\Desktop\New folder\GO\main> 

please someone should help me resolve this code it's giving me headach since two months now.

答案1

得分: 1

你正在尝试访问DB.Create(),但没有将db赋值给全局变量DB

在之前的代码中:

    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})

修改后的代码如下:

    DB, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
英文:

You are trying to access DB.Create() but didn't assign db to global variable DB.
Note: using debugger could prevent a lot of headaches

Before

    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})

After

    DB, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})

huangapple
  • 本文由 发表于 2022年4月30日 06:07:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/72064116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定