目录
Gin是一个使用Go语言开发的Web框架。它提供类似Martini的API,但性能更佳,速度提升高达40倍。官网:Gin Web Framework
安装Gin
新建main.go,写入如下代码:
// main.go
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}
然后构建一个go mod,在当前目录下执行:
go mod init gin-demo
go mod tidy
go mod vendor
然后看到生成的目录结构如下:
然后启动服务:go run main.go,访问 http://127.0.0.1:8080/ping
在Gin框架中查询数据
数据表DDL
CREATE TABLE `user_info` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int DEFAULT '0' COMMENT '用户ID',
`nickname` varchar(50) DEFAULT NULL COMMENT '昵称',
`avatar` varchar(255) DEFAULT NULL COMMENT '头像',
`sex` tinyint DEFAULT '0' COMMENT '性别0=保密 1=男 2=女',
`introduction` varchar(255) DEFAULT NULL COMMENT '简介',
`homepage` varchar(100) DEFAULT NULL COMMENT '个人主页',
`add_time` int DEFAULT '0' COMMENT '添加时间',
`update_time` int DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
配置数据库信息:gin-demo/config/db.go
package config
const (
Mysqldb = "root:123456@tcp(127.0.0.1:3306)/swoft_test?charset=utf8"
)
初始化数据库连接:gin-demo/initDb/db.go
package initDb
import (
"gin-demo/config"
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func Db() *gorm.DB {
db, err := gorm.Open("mysql", config.Mysqldb)
//defer db.Close()
if err != nil {
log.Panicln("err:", err.Error())
}
return db
}
数据model:gin-demo/models/userInfo.go
package models
import (
"gin-demo/initDb"
)
type UserInfo struct {
Id int `json:"id"`
UserId int `json:"userId"`
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
Sex string `json:"sex"`
Introduction string `json:"introduction"`
Homepage string `json:"homepage"`
AddTime int64 `json:"addTime"`
UpdateTime string `json:"updateTime"`
}
func (UserInfo) TableName() string {
return "user_info"
}
func GetUserInfo(userId int) (UserInfo, error) {
var userInfo UserInfo
db := initDb.Db()
rs := db.Where("user_id = ?", userId).First(&userInfo)
return userInfo, rs.Error
}
// 关于 Go ORM 的使用可以参考:https://gorm.io/docs/
控制器:gin-demo/controllers/user.go
package controllers
import (
"gin-demo/models"
"strconv"
"github.com/gin-gonic/gin"
)
func GetUserInfo(c *gin.Context) {
userIdStr := c.Param("userId")
userId, _ := strconv.Atoi(userIdStr)
rs, err := models.GetUserInfo(userId)
if err == nil {
ReturnSuccess(c, 0, "success", rs, 1)
return
}
ReturnError(c, 4004, "没有相关信息")
}
通用方法:gin-demo/controllers/common.go
package controllers
import (
"strconv"
"time"
"github.com/gin-gonic/gin"
)
type JsonStruct struct {
Code int `json:"code"`
Msg interface{} `json:"msg"`
Data interface{} `json:"data"`
Count int `json:"count"`
}
func ReturnSuccess(c *gin.Context, code int, msg interface{}, data interface{}, count int) {
json := &JsonStruct{Code: code, Msg: msg, Data: data, Count: count}
c.JSON(200, json)
}
func ReturnError(c *gin.Context, code int, msg interface{}) {
json := &JsonStruct{Code: code, Msg: msg}
c.JSON(200, json)
}
路由:gin-demo/router/router.go
package router
import (
"gin-demo/config"
"gin-demo/controllers"
"net/http"
"github.com/gin-gonic/gin"
)
func Router() *gin.Engine {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": config.Mysqldb,
})
})
// 健康检查接口
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"success": true,
})
})
user := r.Group("/user")
{
user.GET("/info/:userId", controllers.GetUserInfo)
}
return r
}
入口文件:gin-demo/main.go
package main
import (
"gin-demo/router"
)
func main() {
r := router.Router()
r.Run(":8080") // listen and serve on 0.0.0.0:8080
}
启动:go run main.go
浏览器访问:http://127.0.0.1:8080/user/info/1
在Go中接入Consul
在前几天我分别用原生PHP、PHP的Swoft框架接入了微服务Consul,具体内容参考:
PHP中接入consul,实现微服务的注册发现和配置中心_浮尘笔记的博客-CSDN博客
Swoft中使用Consul微服务_浮尘笔记的博客-CSDN博客
由于Consul是使用go语言开发的服务发现、配置管理中心服务,因此本文演示一下在Go中实现接入Consul微服务。
consul 配置文件:config/consul.go
package config
const (
Address = "127.0.0.1:8500"
CheckHttp = "http://127.0.0.1:8080/health"
)
gin-demo/consul/api.go
package consul
import (
"fmt"
"gin-demo/config"
"github.com/hashicorp/consul/api"
)
func Register(address string, port int, name string, tags []string, id string) error {
cfg := api.DefaultConfig()
cfg.Address = config.Address
client, err := api.NewClient(cfg)
if err != nil {
panic(err)
}
//生成对应的检查对象
check := &api.AgentServiceCheck{
HTTP: config.CheckHttp,
Timeout: "5s",
Interval: "5s",
DeregisterCriticalServiceAfter: "10s",
}
//生成注册对象
registration := new(api.AgentServiceRegistration)
registration.Name = name
registration.ID = id
registration.Port = port
registration.Tags = tags
registration.Address = address
registration.Check = check
err = client.Agent().ServiceRegister(registration)
if err != nil {
panic(err)
}
return nil
}
// 根据ID获取服务
func GetServiceByID(id string) {
cfg := api.DefaultConfig()
cfg.Address = config.Address
client, err := api.NewClient(cfg)
if err != nil {
panic(err)
}
data, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service == %s", id))
if err != nil {
panic(err)
}
svrHost := ""
svrPort := 0
for key, value := range data {
svrHost = value.Address
svrPort = value.Port
fmt.Println("获取到服务:" + key)
fmt.Println("IP:PORT", svrHost, svrPort)
}
}
入口文件 main.go
package main
import (
"gin-demo/consul"
"gin-demo/router"
)
func main() {
r := router.Router()
consul.Register("127.0.0.1", 8801, "goUserHttp", []string{"go"}, "goUserHttp")
r.Run(":8080") // listen and serve on 0.0.0.0:8080
}
启动 Consul:consul agent -dev
启动 Gin 服务:go run main.go
打开Consul控制台:http://127.0.0.1:8500/
可以看到刚才添加的服务已经注册进去了。
然后,把之前 PHP swoft 的微服务也启动起来,源代码:swoft-demo-2023: PHP的Swoft框架的代码演示
php user/bin/swoft http:start
在Go项目中尝试获取上面的 swoftUser 服务:
// gin-demo/main.go
consul.GetServiceByID("swoftUser")