编写.api文件
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
syntax = "v1"
type Request {
UserName string `json:"username"`
PassWord string `json:"password"`
}
type Response {
UserId int64 `json:"user_id"`
}
service auth {
@handler login
post /api/user/login (Request) returns (Response)
}
生成相关代码
- 01
goctl api go -api user.api -dir .
![](https://blog.meowrain.cn/api/i/2024/09/26/9XJKdC1727317723827507088.webp)
![](https://blog.meowrain.cn/api/i/2024/09/26/W0Q5Pd1727317739564810959.webp)
使用go mod tidy
安装相关库
![](https://blog.meowrain.cn/api/i/2024/09/26/W0pOhD1727317905026044889.webp)
我们能看到auth.yaml
里面的相关配置
![](https://blog.meowrain.cn/api/i/2024/09/26/ictk2q1727317953381822122.webp)
接下来我们要写死用户名和密码,让service从config中读进去,然后在logic中进行判断,完成响应
编写 auth.yaml
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Name: auth
Host: 0.0.0.0
Port: 8888
User:
UserName: "meowrain"
Password: "123456"
编写config.go
因为修改了yaml配置文件,想让go能解构其中内容到结构体上,我们需要修改config.go
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
package config
import "github.com/zeromicro/go-zero/rest"
type Config struct {
rest.RestConf
User struct {
UserName string
Password string
}
}
修改logic,进行鉴权
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
package logic
import (
"context"
"user/internal/svc"
"user/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type LoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
return &LoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *LoginLogic) Login(req *types.Request) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
if req.UserName == l.svcCtx.Config.User.UserName && req.PassWord == l.svcCtx.Config.User.Password {
return &types.Response{
UserId: int64(1),
}, nil
}
return
}
运行auth.go
![](https://blog.meowrain.cn/api/i/2024/09/26/eqzali1727318393904403434.webp)
我们来测试一下
- 01
curl -X POST -H "Content-Type: application/json" -d '{"username":"meowrain","password":"123456"}' http://127.0.0.1:8888/api/user/login
![](https://blog.meowrain.cn/api/i/2024/09/26/s7KPs01727318537953352751.webp)
可以看到已经响应了