Skip to content

Commit

Permalink
feat: add kitex_swagger_gen example (#161)
Browse files Browse the repository at this point in the history
  • Loading branch information
EZ4Jam1n authored Oct 15, 2024
1 parent d739c15 commit a299116
Show file tree
Hide file tree
Showing 37 changed files with 60,817 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ You can go into the related examples for information on "how to run"
- [bizdemo/kitex_gorm_gen](bizdemo/kitex_gorm_gen) Example of using Kitex and gorm_gen
- [bizdemo/kitex_zorm](bizdemo/kitex_zorm) Example of using Kitex and zorm
- [bizdemo/kitex_ent](bizdemo/kitex_ent) Example of using Kitex and ent
- [bizdemo/kitex_swagger_gen](bizdemo/kitex_swagger_gen) Example of using Kitex and swagger generate
- [bizdemo/easy_note](bizdemo/easy_note) Example of using Kitex as a rpc framework to implement a simple note service with multiple middlewares
- [Bookinfo](https://github.com/cloudwego/biz-demo/tree/main/bookinfo) Example of using Kitex as the rpc framework to implement multi-functional book service programs including Istio, OpenTelemetry, etc.
- [Open Payment Platform](https://github.com/cloudwego/biz-demo/tree/main/open-payment-platform) Example of using Kitex as the rpc framework to demonstrate the usage of Kitex generic call, and builds an integrated payment platform.
Expand Down
1 change: 1 addition & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- [bizdemo/kitex_gorm_gen](bizdemo/kitex_gorm_gen) 使用 Kitex 和 gorm_gen 的示例
- [bizdemo/kitex_zorm](bizdemo/kitex_zorm) 使用 Kitex 和 zorm 的示例
- [bizdemo/kitex_ent](bizdemo/kitex_ent) 使用 Kitex 和 ent 的示例
- [bizdemo/kitex_swagger_gen](bizdemo/kitex_swagger_gen) 使用 Kitex 和 swagger 生成的示例
- [bizdemo/easy_note](bizdemo/easy_note) 使用 Kitex 作为 rpc 框架实现多中间件简易笔记服务的示例
- [Bookinfo](https://github.com/cloudwego/biz-demo/tree/main/bookinfo) 使用 Kitex 作为 rpc 框架实现包含 istio 服务网格,OpenTelemetry 监控等多功能书籍服务程序的示例
- [Open Payment Platform](https://github.com/cloudwego/biz-demo/tree/main/open-payment-platform) 使用 Kitex 作为 rpc 框架演示了 Kitex 泛化调用的用法,构建了一体化支付平台
Expand Down
1 change: 1 addition & 0 deletions bizdemo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Basic examples of kitex framework and ORM. For advanced examples of obs, load ba
- [bizdemo/kitex_gorm_gen](bizdemo/kitex_gorm_gen) Example of using kitex and gorm_gen
- [bizdemo/kitex_zorm](bizdemo/kitex_zorm) Example of using kitex and zorm
- [bizdemo/kitex_zorm](bizdemo/kitex_zorm) Example of using kitex and ent
- [bizdemo/kitex_swagger_gen](bizdemo/kitex_swagger_gen) Example of using kitex and swagger generate

Integrated more components and more complete biz-demo
- [bizdemo/easy_note](bizdemo/easy_note) Example of using kitex as an rpc framework to implement a simple note service with multiple middlewares
Expand Down
2 changes: 2 additions & 0 deletions bizdemo/kitex_swagger_gen/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
init_user/update_user:
kitex -service user -module github.com/cloudwego/kitex-examples/bizdemo/kitex_swagger_gen -thrift-plugin rpc-swagger ./idl/user.thrift
47 changes: 47 additions & 0 deletions bizdemo/kitex_swagger_gen/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# kitex_swagger_gen

## Introduction

An example using `Kitex` and `thrift-gen-rpc-swagger`.

- Defines `RPC` interfaces using `thrift` IDL
- Generates code using `Kitex`
- Utilizes `Gorm` and `MySQL`
- Uses the `thrift-gen-rpc-swagger` plugin to generate `Swagger` files and a `Swagger UI` service

- `/swagger` provides the `Swagger` files and `Swagger UI` server
- `/handler.go` contains the basic logic for updating, adding, deleting, querying users and examples using `metainfo`

## IDL

This example defines `RPC` interfaces using `thrift` IDL. The specific interface definitions can be found in [user.thrift](idl/user.thrift).

## Code Generation Tools

This example uses `Kitex` for code generation. For more information on how to use `Kitex`, refer to the [Kitex documentation](https://www.cloudwego.io/docs/kitex/tutorials/code-gen/).

The `Kitex` commands used can be found in the [Makefile](Makefile).

## Plugins

`thrift-gen-rpc-swagger` generates `Swagger` documentation and a `Swagger UI` service through code generation.

For more details, refer to [swagger-generate](https://github.com/hertz-contrib/swagger-generate).

## How to Run

### Running MySQL Docker

```bash
cd bizdemo/kitex_swagger_gen && docker-compose up
```

### Running the Example

```bash
cd bizdemo/kitex_swagger_gen
go run .

cd bizdemo/kitex_swagger_gen/downstream_server
go run .
```
47 changes: 47 additions & 0 deletions bizdemo/kitex_swagger_gen/README_CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# kitex_swagger_gen

## 介绍

一个使用 `Kitex``thrift-gen-rpc-swagger` 的示例。

- 使用 `thrift` IDL 定义 `RPC` 接口
- 使用 `kitex` 生成代码
- 使用 `Gorm` and `MySQL`
- 使用 `thrift-gen-rpc-swagger` 插件生成 `swagger` 文件和 `swagger ui` 服务

- `/swagger` 提供 `swagger` 文件和 `swagger ui` 服务器
- `/hander.go` 包含更新用户、添加用户、删除用户、查询用户的基础逻辑以及使用`metainfo`的示例

## IDL

该示例使用 `thrift` IDL 来定义 `RPC` 接口。具体的接口定义在 [user.thrift](idl/user.thrift) 中。

## 代码生成工具

该示例使用 `kitex` 来生成代码。`kitex` 的使用可以参考 [kitex](https://www.cloudwego.io/docs/kitex/tutorials/code-gen/)

使用的 `kitex` 命令可以在 [Makefile](Makefile) 中找到。

## 插件

`thrift-gen-rpc-swagger` 通过代码生成的`swagger`文档和`swagger ui`服务。

详情可参考 [swagger-generate](https://github.com/hertz-contrib/swagger-generate)

## 如何运行

### 运行 MySQL docker

```bash
cd bizdemo/kitex_swagger_gen && docker-compose up
```

### 运行示例

```bash
cd bizdemo/kitex_swagger_gen
go run .

cd bizdemo/kitex_swagger_gen/downstream_server
go run .
```
12 changes: 12 additions & 0 deletions bizdemo/kitex_swagger_gen/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
RUN_NAME="user"

mkdir -p output/bin
cp script/* output/
chmod +x output/bootstrap.sh

if [ "$IS_SYSTEM_TEST_ENV" != "1" ]; then
go build -o output/bin/${RUN_NAME}
else
go test -c -covermode=set -o output/bin/${RUN_NAME} -coverpkg=./...
fi
23 changes: 23 additions & 0 deletions bizdemo/kitex_swagger_gen/dao/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dao

import "github.com/cloudwego/kitex-examples/bizdemo/kitex_swagger_gen/dao/mysql"

func init() {
mysql.Init()
}
39 changes: 39 additions & 0 deletions bizdemo/kitex_swagger_gen/dao/mysql/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package mysql

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

var dsn = "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local"

var DB *gorm.DB

func Init() {
var err error
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
SkipDefaultTransaction: true,
PrepareStmt: true,
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic(err)
}
}
48 changes: 48 additions & 0 deletions bizdemo/kitex_swagger_gen/dao/mysql/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package mysql

import "github.com/cloudwego/kitex-examples/bizdemo/kitex_swagger_gen/model"

func CreateUser(users []*model.User) error {
return DB.Create(users).Error
}

func DeleteUser(userId int64) error {
return DB.Where("id = ?", userId).Delete(&model.User{}).Error
}

func UpdateUser(user *model.User) error {
return DB.Updates(user).Error
}

func QueryUser(keyword *string, page, pageSize int64) ([]*model.User, int64, error) {
db := DB.Model(model.User{})
if keyword != nil && len(*keyword) != 0 {
db = db.Where(DB.Or("name like ?", "%"+*keyword+"%").
Or("introduce like ?", "%"+*keyword+"%"))
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
var res []*model.User
if err := db.Limit(int(pageSize)).Offset(int(pageSize * (page - 1))).Find(&res).Error; err != nil {
return nil, 0, err
}
return res, total, nil
}
14 changes: 14 additions & 0 deletions bizdemo/kitex_swagger_gen/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
version: '3'

services:
mysql:
image: 'mysql:latest'
volumes:
- ./biz/model/sql:/docker-entrypoint-initdb.d
ports:
- 9910:3306
environment:
- MYSQL_DATABASE=gorm
- MYSQL_USER=gorm
- MYSQL_PASSWORD=gorm
- MYSQL_RANDOM_ROOT_PASSWORD="yes"
84 changes: 84 additions & 0 deletions bizdemo/kitex_swagger_gen/downstream_server/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package main

import (
"context"
"log"

"github.com/bytedance/gopkg/cloud/metainfo"
"github.com/cloudwego/kitex-examples/bizdemo/kitex_swagger_gen/kitex_gen/user"
"github.com/cloudwego/kitex-examples/bizdemo/kitex_swagger_gen/kitex_gen/user/userservice"
"github.com/cloudwego/kitex/pkg/utils"
"github.com/cloudwego/kitex/server"
)

// UserService2Impl implements the last service interface defined in the IDL.
type UserService2Impl struct{}

// UpdateUser implements the UserServiceImpl interface.
func (s *UserService2Impl) UpdateUser(ctx context.Context, req *user.UpdateUserRequest) (resp *user.UpdateUserResponse, err error) {
t1, _ := metainfo.GetPersistentValue(ctx, "p_k")
t2, _ := metainfo.GetValue(ctx, "k")

return &user.UpdateUserResponse{
Code: user.Code_Success,
Msg: " 持续元信息->" + t1 + " 临时元信息->" + t2,
}, nil
}

// DeleteUser implements the UserServiceImpl interface.
func (s *UserService2Impl) DeleteUser(ctx context.Context, req *user.DeleteUserRequest) (resp *user.DeleteUserResponse, err error) {
t1, _ := metainfo.GetPersistentValue(ctx, "p_k")
t2, _ := metainfo.GetValue(ctx, "k")

return &user.DeleteUserResponse{
Code: user.Code_Success,
Msg: " 持续元信息->" + t1 + " 临时元信息->" + t2,
}, nil
}

// QueryUser implements the UserServiceImpl interface.
func (s *UserService2Impl) QueryUser(ctx context.Context, req *user.QueryUserRequest) (resp *user.QueryUserResponse, err error) {
t1, _ := metainfo.GetPersistentValue(ctx, "p_k")
t2, _ := metainfo.GetValue(ctx, "k")

return &user.QueryUserResponse{
Code: user.Code_Success,
Msg: " 持续元信息->" + t1 + " 临时元信息->" + t2,
}, nil
}

// CreateUser implements the UserServiceImpl interface.
func (s *UserService2Impl) CreateUser(ctx context.Context, req *user.CreateUserRequest) (resp *user.CreateUserResponse, err error) {
t1, _ := metainfo.GetPersistentValue(ctx, "p_k")
t2, _ := metainfo.GetValue(ctx, "k")

return &user.CreateUserResponse{
Code: user.Code_Success,
Msg: " 持续元信息->" + t1 + " 临时元信息->" + t2,
}, nil
}

func main() {
svr := userservice.NewServer(new(UserService2Impl), server.WithServiceAddr(utils.NewNetAddr("tcp", ":8889")))

err := svr.Run()
if err != nil {
log.Println(err.Error())
}
}
Loading

0 comments on commit a299116

Please sign in to comment.