go--写一个简单的接口

参考了这篇文章
https://blog.csdn.net/u010129985/article/details/81744357
https://blog.csdn.net/weixin_38166686/article/details/101166631

环境

go.mod 及 go version如下


code

表结构如下


package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

// var db *auto-clean.DB
var db *gorm.DB
var err error

type App_info struct {
        Ip            string   `json:"ip"`
        Cluster_info  string   `json:"cluster_info"`
        App_id        uint   `json:"app_id"`
}

func main() {
    // NOTE: See we’re using = to assign the global var
    // instead of := which would assign it only in this function
    db, err = gorm.Open("sqlite3", "./auto-clean.db")
    if err != nil {
        fmt.Println(err)
    }
    defer db.Close()
    db.SingularTable(true)
    // db.AutoMigrate(&App_info{})
    r := gin.Default()

    r.GET("/", GetProjects)
    r.GET("/info/:ip", GetInfo)
    // r.POST("/info", CreateInfo)

    r.Run(":8080")
}

func GetProjects(c *gin.Context) {
    var v1 []App_info
    if err := db.Find(&v1).Error; err != nil {
        c.AbortWithStatus(404)
        fmt.Println(err)
    } else {
        c.JSON(200, v1)
    }
}

func GetInfo(c *gin.Context) {
    ip := c.Params.ByName("ip")
    var v1 App_info
    if err := db.Where("ip = ?", ip).First(&v1).Error; err != nil {
        c.AbortWithStatus(404)
        fmt.Println(err)
    } else {
        c.JSON(200, v1)
    }
}

func CreateInfo(c *gin.Context) {
    var v1 App_info
    c.BindJSON(&v1)
    db.Create(&v1)
    c.JSON(200, v1)
}

运行及结果


推荐阅读更多精彩内容