install
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
技术选型: gorm(sqlite),go-fiber
开发
database/database.go
package database
import (
"gorm.io/gorm"
)
var (
DBConn *gorm.DB
)
lead/lead.go
package lead
import (
"errors"
"go_fiber_crm/database"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
type Lead struct {
gorm.Model
Name string `json:"name"`
Company string `json:"company"`
Email string `json:"email"`
Phone int `json:"phone"`
}
func GetLead(c *fiber.Ctx) error {
id := c.Params("id")
db := database.DBConn
var lead Lead
db.Find(&lead, id)
c.JSON(lead)
return nil
}
func GetLeads(c *fiber.Ctx) error {
db := database.DBConn
var leads []Lead
db.Find(&leads)
c.JSON(leads)
return nil
}
func NewLead(c *fiber.Ctx) error {
db := database.DBConn
// 在 golang 中 new 是另外一种创建变量的方式。
// 通过 new(T) 可以创建 T 类型的变量(这里 T 表示类型)
// 初始值为 T 类型的零值,返回值为其地址(地址类型是 *T)。
lead := new(Lead) // 返回指向类型的指针
if err := c.BodyParser(lead); err != nil {
c.Status(503).SendString(err.Error())
return err
}
db.Create(&lead)
c.JSON(lead)
return nil
}
func UptLead(c *fiber.Ctx) error {
id := c.Params("id")
db := database.DBConn
var old Lead
db.First(&old, id)
if old.Name == "" {
c.Status(500).SendString("no lead found with ID")
return errors.New("no lead found with ID")
}
// 传过来要修改的数据
newLead := new(Lead)
if err := c.BodyParser(newLead); err != nil {
c.Status(503).SendString(err.Error())
return err
}
if newLead.Name != "" {
old.Name = newLead.Name
}
if newLead.Company != "" {
old.Company = newLead.Company
}
if newLead.Email != "" {
old.Email = newLead.Email
}
if newLead.Phone != 0 {
old.Phone = newLead.Phone
}
db.Save(old)
c.JSON(old)
return nil
}
func DeleteLead(c *fiber.Ctx) error {
id := c.Params("id")
db := database.DBConn
var lead Lead
db.First(&lead, id)
if lead.Name == "" {
c.Status(500).SendString("no lead found with ID")
return errors.New("no lead found with ID")
}
db.Delete(&lead)
c.SendString("lead successfully deleted")
return nil
}
main.go
package main
import (
"fmt"
"go_fiber_crm/database"
"go_fiber_crm/lead"
"github.com/gofiber/fiber/v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func setupRoutes(app *fiber.App) {
api := app.Group("/api")
v1 := api.Group("/v1")
v1.Get("/lead", lead.GetLeads)
v1.Get("/lead/:id", lead.GetLead)
v1.Post("/lead", lead.NewLead)
v1.Put("/lead/:id",lead.UptLead)
v1.Delete("/lead/:id", lead.DeleteLead)
}
func initDatabase() {
var err error
database.DBConn, err = gorm.Open(sqlite.Open("leads.db"), &gorm.Config{})
if err != nil {
panic("failed to open database")
}
fmt.Println("connect to database")
database.DBConn.AutoMigrate(&lead.Lead{})
fmt.Println("database migrated")
}
func main() {
app := fiber.New()
initDatabase()
setupRoutes(app)
app.Listen(":3000")
// defer database.DBConn.Close()
}