跳到主要内容
版本:2.8.x(Latest)

接下来,我们要在控制器里调用微服务,完成具体的业务逻辑。

实际开发中,复杂业务逻辑需要封装到logic中,像Web单体服务一样,由控制器调用。

用户服务


app/gateway/internal/controller/user/user_v1_login.go

package user  

import (
"context"

account "proxima/app/user/api/account/v1"

"proxima/app/gateway/api/user/v1"
)

func (c *ControllerV1) Login(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
user, err := c.AccountClient.UserLogin(ctx, &account.UserLoginReq{
Username: req.Username,
Password: req.Password,
})

if err != nil {
return nil, err
}

return &v1.LoginRes{
Token: user.GetToken(),
}, nil
}

发起请求测试,网关调用微服务是否成功:

$ curl -X POST http://127.0.0.1:8000/v1/users/login \
-H "Content-Type: application/json" \
-d '{
"username": "oldme",
"password": "12345678"
}'

{
  "code": 0,
  "message": "",
  "data": {
  "token": "I am token"
  }
}

看到这个返回结果,恭喜您,大功告成。接下来,您可以尝试把其他的几个服务也开发出来。这里我贴出源码,您可以对照着看看。

单词服务


app/gateway/internal/controller/words/words_v1_create.go

package words  

import (
"context"

words "proxima/app/word/api/words/v1"

"proxima/app/gateway/api/words/v1"
)

func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
_, err = c.WordsClient.Create(ctx, &words.CreateReq{
Uid: 1,
Word: req.Word,
Definition: req.Definition,
})

if err != nil {
return nil, err
}

return &v1.CreateRes{}, nil
}

app/gateway/internal/controller/words/words_v1_detail.go

package words  

import (
"context"

"github.com/gogf/gf/v2/errors/gerror"
words "proxima/app/word/api/words/v1"

"proxima/app/gateway/api/words/v1"
)

func (c *ControllerV1) Detail(ctx context.Context, req *v1.DetailReq) (res *v1.DetailRes, err error) {
word, err := c.WordsClient.Get(ctx, &words.GetReq{
Id: uint32(req.Id),
})

if err != nil {
return nil, err
}

if word == nil {
return nil, gerror.New("word not found")
}

return &v1.DetailRes{
Id: uint(word.Words.Id),
Word: word.Words.Word,
Definition: word.Words.Definition,
}, nil
}