Gin实现简单接口

本来想用gin_scaffold这个写web,但是这个框架作者用了自己封装的golang_common来初始化数据库,以及引用了自己的Gorm,所以打算参考作者的项目结构,用原生的Gorm写,

简单实现的两个接口:

controller:

package controller

import (
    "Initial/conf"
    "Initial/dao"
    "github.com/gin-gonic/gin"
    "net/http"
)

type UserController struct {}

func UserRegister(router *gin.RouterGroup){
    user := UserController{}
    router.GET("/index", user.GetUserMessages)
    router.POST("/create", user.CreateUser)
}


func (userControl *UserController) CreateUser(c *gin.Context) {
    var user dao.User
    name := c.PostForm("name")
    if name != "" {
        user.Name = name
    }
    errBindData := c.BindJSON(&user)
    if errBindData != nil{
        return
    }
    err := dao.CreateUser(conf.Db, &user)
    if err != nil {
        c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
        return
    }
    c.JSON(http.StatusOK, user)
}


func (userControl *UserController)GetUserMessages(c *gin.Context){
    var user []dao.User
    err := dao.FindAllUser(conf.Db, &user)
    if err != nil{
        c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
        return
    }
    c.JSON(http.StatusOK, user)
}

dao/user.go

package dao

import (
    "gorm.io/gorm"
    "time"
)

type User struct {
    ID int
    Name string
    CreatedTime time.Time
}


//get users
func FindAllUser(db *gorm.DB, user *[]User) (err error) {
    err = db.Find(&user).Error
    if err != nil{
        return  err
    }
    return nil
}

//create a user
func CreateUser(db *gorm.DB, User *User)  (err error) {
    err = db.Create(User).Error
    if err != nil {
        return err
    }
    return nil
}

//get user by id
func GetUser(db *gorm.DB, User *User, id string) (err error) {
    err = db.Where("id = ?", id).First(User).Error
    if err != nil {
        return err
    }
    return nil
}

//update user
func UpdateUser(db *gorm.DB, User *User) (err error) {
    db.Save(User)
    return nil
}

//delete user
func DeleteUser(db *gorm.DB, User *User, id string) (err error) {
    db.Where("id = ?", id).Delete(User)
    return nil
}

router添加

    userRouter := router.Group("/user")
    {
        controller.UserRegister(userRouter)
    }

main.go

package main

import (
    "Initial/conf"
    "Initial/router"
    "os"
    "os/signal"
    "syscall"
)

func main()  {
    conf.InitDb()
    err := router.InitRouter().Run(":8880")
    if err != nil{
        return
    }

    quit := make(chan os.Signal)
    signal.Notify(quit, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGTERM)
    <-quit

}

目前是在conf里面初始化数据库conf/db.go

package conf

import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

const DbUsername = "root"
const DbPassword = "123456"
const DbName = "more"
const DbHost = "127.0.0.1"
const DbPort = "3306"


var Db *gorm.DB
func InitDb() *gorm.DB {
    Db = connectDB()
    return Db
}

func connectDB() *gorm.DB {
    var err error
    dsn := DbUsername +":"+ DbPassword +"@tcp"+ "(" + DbHost + ":" + DbPort +")/" + DbName + "?" + "parseTime=true&loc=Local"

    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

    if err != nil {
        fmt.Printf("Error connecting to database : error=%v\n", err)
        return nil
    }

    return db
}

 

 

 

 

 数据是成功保存了,剩下的这个报错待解决。

已解决:

 

 gin绑定参数的问题:

 

posted @ 2021-06-08 23:48  青花メ  阅读(494)  评论(0编辑  收藏  举报