go-zore 笔记
大约 1 分钟
etc 安装
https://github.com/etcd-io/etcd/releases
安装
api 设计
api格式化
goctl api format --dir user.api
api 代码生成
mkdir code
cd code
go mod init project_name
goctl api new user
修改了 .api
文件重新生成代码
goctl api go -api user.api -dir .
RPC 代码生成
goctl rpc new rpc
服务注册
中间件使用
跨域处理
main.go
server := rest.MustNewServer(
c.RestConf,
rest.WithCors("*"), // 跨域处理
)
defer server.Stop()
返回结果处理
返回
syntax = "v1"
type LoginRequest {
Name string `path:"name,options=you|me"`
}
type LoginResponse {
Message string `json:"message"`
}
type ResSuccess {
Code int `json:"code" default:200`
Msg string `json:"msg" default:"success"`
}
type ResError {
Code int `json:"code" default:202`
Msg string `json:"msg" default:"error"`
}
type ResData {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type ResList {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
Total int64 `json:"total"`
}
gorm 集成
填写配置文件
db:
host: localhost
port: 3306
user: root
password: 123456
database: go_zero
加载配置文件
package config
import (
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
DB Db
}
type Db struct {
Host string
Port int
User string
Password string
Database string
}
初始化数据库
jwt 验证
go get github.com/golang-jwt/jwt/v4
package config
import (
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
DB Db
Auth struct {
AccessSecret string
AccessExpire int64
}
}
type Db struct {
Host string
Port int
User string
Password string
Database string
}
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/user/info",
Handler: user.InfoHandler(serverCtx),
},
},
rest.WithPrefix("/v1"),
rest.WithJwt(serverCtx.Config.Auth.AccessSecret), // 开启jwt的验证
)