Gin实现简单接口

Posted 青花メ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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绑定参数的问题:

 

以上是关于Gin实现简单接口的主要内容,如果未能解决你的问题,请参考以下文章

golang : gorm + gin实现restful 分页接口

编程实践Go Web开发:使用Gin快速实现一个HTTP接口

#yyds干货盘点# Golang Gin 框架上传介绍

Golang Gin 框架上传介绍

gin框架实现一个简单的项目 ③

Gin编写图床后端-上传图片代码实现