go微服务开发:Mac下使用kratos框架进行接口开发的教程

背景:

Mac 13.5.2 + kratos + docker + mysql 8.0.14 + navicat 16

 

在使用kratos进行接口开发之前,假设你已经安装了 go 、protoc 、protoc-gen-go 、 kratos,如果还没有安装,请先执行下面的命令进行安装:

brew install go
brew install protobuf
brew install protoc-gen-go
go install github.com/go-kratos/kratos/cmd/kratos/v2@latest

 参考 https://www.jb51.cc/note/4121304.html

 

一、准备工作:

1 使用brew安装docker

brew install --cask docker

 

2 使用docker安装mysql 8镜像

docker pull mysql

 

3 解决github页面加载显示不完整

在网上找了几个资料,只有这个是可行的

sudo vim /etc/hosts

140.82.112.4 github.com
185.199.108.154 github.githubassets.com
185.199.109.154 github.githubassets.com
185.199.110.154 github.githubassets.com
185.199.111.154 github.githubassets.com

保存以后,为了确保生效,执行下面的命令:

sudo killall -HUP mDNSResponder
sudo dscacheutil -flushcache

 

4 安装navicat 16

 网盘的下载地址是 https://pan.baidu.com/s/1GvN5SMg4S50ZDLhApboqsA

 解压不需要密码,解压出来有安装说明,安装说明进行操作即可,汉化的说明也有,这里就不再赘述了。

 

5 安装curlie和bloomrpc

安装curlie比较简单,执行 brew install curlie

安装bloomrpc就比较麻烦了,网络不能慢,是大前提,因为需要用到界面,需要加 --cask 参数,执行 brew install --cask bloomrpc ,这个安装过程,根据你的网络情况而定,失败的话,就多尝试几次,也可以试着给brew换成国内源,但是不推荐这么做,因为给brew换源,之前通过brew安装的程序会受到影响,需要重新安装,要不要换源,请自行斟酌。

确要为brew换源,打开terminal,执行下面的命令:

/bin/bash -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"

使用阿里源,会快一点,你也可以选择其他的。

更多brew换源的说明,请参考:https://www.jianshu.com/p/e0c34c036fcc

 

6 初始化kratos的项目模版

# 使用cli命令初始化
kratos new helloworld

# 也可以使用kratos-layout初始化
kratos new helloworld -r https://gitee.com/go-kratos/kratos-layout.git

# 安装依赖
go mod download

# 生成项目代码
go generate ./...

 

二、使用kratos进行开发接口

1 生成student.proto,执行下面的命令

kratos proto add api/helloworld/v1/student.proto

 1.1 定义GetStudent接口

    rpc GetStudent (GetStudentRequest) returns (GetStudentReply) {
        option (google.api.http) = {
            get: "/student/{id}",
        };
    }

1.2 定义GetStudent的请求和响应结构体

message GetStudentRequest {
    int32  id = 1;
}

message GetStudentReply {
    string         name                 = 1;
    int32         status             = 2;
    int32          id                     = 3;
    string         info                 = 4;
}

 

2 生成student.proto对应的pb文件

kratos proto client api/helloworld/v1/student.proto

 也可以使用 make api,和上面的命令是一样的。

 

3 为student生成service,执行下面的命令

kratos proto server api/helloworld/v1/student.proto -t internal/service

 

 

参考资料:

https://blog.csdn.net/jkwanga/article/details/128319158

https://blog.csdn.net/qq_43280993/article/details/129703277

https://www.lxlinux.net/6027.html

https://www.cnblogs.com/liyugui/p/17627854.html

https://zhuanlan.zhihu.com/p/545368410

posted @ 2023-09-23 17:30  jamstack  阅读(283)  评论(0编辑  收藏  举报