这个分两步,一个是打通对外的接口,一个是打通网关
用gin起对外的接口
1.修改 proto/user_api.proto
syntax = "proto3";
package user_srv;
option go_package = "./proto;user_srv";
service User_srv {
rpc GetUserInfo(RequestUserId) returns (ResponseUserInfo) {}
}
message RequestUserId {
int64 userId = 1;
}
message ResponseUserInfo {
string accountName = 1;
string userName = 2;
string passWord = 3;
string department = 4;
string email = 5;
string status = 6;
int32 role = 7;
}
之后执行make proto
2.创建api文件夹
mkdir api
cd api
vim user.go
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
func GetUserInfo(ctx *gin.Context) {
ctx.JSON(http.StatusOK,
gin.H{
"code": 200,
"total": "ok",
"accounts": "获取用户信息",
})
}
3.创建routers文件夹
mkdir routers
cd routers
vim routers
package routers
import (
"user_api/api"
"github.com/gin-gonic/gin"
)
func InitRouters() *gin.Engine {
ginRouter := gin.Default()
ginRouter.GET("/users/", func(context *gin.Context) {
context.String(200, "get userinfos")
})
ginRouter.GET("/getUserInfo/", api.GetUserInfo)
return ginRouter
}
4.创建global,存储公共链接
mkdir golabl
cd golabl
vim global
package global
import (
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-plugins/registry/consul/v2"
)
var (
//consul链接
ConsulClient = consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
)
5.编写main.go
package main
import (
"user_api/global"
"user_api/routers"
"github.com/micro/go-micro/v2/web"
)
func main() {
//3. 初始化routers
ginRouter := routers.InitRouters()
consulReg := global.ConsulClient
//注册服务
microService := web.NewService(
web.Name("user.client"),
web.Address(":18001"),
web.Registry(consulReg),
web.Handler(ginRouter),
)
err := microService.Run()
if err != nil {
return
}
}
6.执行go mod tidy,更新依赖包,运行main.go
到这已经运行成功,并且注册到consul
访问端口我这里设置成本机的18001 端口
127.0.01:18001/users/
127.0.01:18001/getUserInfo/
项目地址
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)