编写.api文件

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)
}



生成相关代码

goctl api go -api user.api -dir .

使用go mod tidy 安装相关库

我们能看到auth.yaml里面的相关配置

接下来我们要写死用户名和密码,让service从config中读进去,然后在logic中进行判断,完成响应

编写 auth.yaml

Name: auth
Host: 0.0.0.0
Port: 8888
User:
  UserName: "meowrain"
  Password: "123456"

编写config.go

因为修改了yaml配置文件,想让go能解构其中内容到结构体上,我们需要修改config.go

package config

import "github.com/zeromicro/go-zero/rest"

type Config struct {
	rest.RestConf
	User struct {
		UserName string
		Password string
	}
}

修改logic,进行鉴权

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

我们来测试一下

curl -X POST -H "Content-Type: application/json" -d '{"username":"meowrain","password":"123456"}' http://127.0.0.1:8888/api/user/login

可以看到已经响应了