mirror of https://github.com/zhufuyi/sponge
docs: update README
This commit is contained in:
parent
5110a00f66
commit
eaafdff62d
14
README.md
14
README.md
|
@ -62,7 +62,7 @@ Additionally, developers can use custom templates to generate various types of c
|
|||
5. **Built-in AI assistant generates business logic implementation code**
|
||||
Sponge comes with a built-in AI assistant (ChatGPT and DeepSeek), combining the strengths of both to form a comprehensive and efficient development solution:
|
||||
- **Sponge**: Handles infrastructure code generation (service framework, CRUD API interfaces, and custom API interfaces without business logic implementation).
|
||||
- **DeepSeek or ChatGPT**: Focuses on business logic implementation (table structure DDL design, custom API interface definition, and business logic implementation code).
|
||||
- **AI assistant**: Focuses on business logic implementation (table structure DDL design, custom API interface definition, and business logic implementation code).
|
||||
|
||||
<br>
|
||||
|
||||
|
@ -70,7 +70,7 @@ Additionally, developers can use custom templates to generate various types of c
|
|||
|
||||
1. **Install sponge**
|
||||
|
||||
Sponge supports installation on Windows, macOS, and Linux. Click to view the [**sponge installation guide**](https://github.com/go-dev-frame/sponge/blob/main/assets/install-cn.md).
|
||||
Sponge supports installation on Windows, macOS, and Linux. Click to view the [**sponge installation guide**](https://github.com/go-dev-frame/sponge/blob/main/assets/install-en.md).
|
||||
|
||||
2. **Open the code generation UI**
|
||||
|
||||
|
@ -86,7 +86,7 @@ Additionally, developers can use custom templates to generate various types of c
|
|||
<img width="1500px" src="https://raw.githubusercontent.com/go-dev-frame/sponge/main/assets/en_sponge-ui.png">
|
||||
</p>
|
||||
|
||||
> To access from a browser on a different host, specify the host IP or domain when starting the UI, e.g., `sponge run -a http://your_host_ip:24631`. Alternatively, you can run the UI service in Docker to support cross-host access. Click to view the guide on [running the sponge UI service in Docker](https://github.com/go-dev-frame/sponge/blob/main/assets/install-cn.md#Docker%E7%8E%AF%E5%A2%83).
|
||||
> To access from a browser on a different host, specify the host IP or domain when starting the UI, e.g., `sponge run -a http://your_host_ip:24631`. Alternatively, you can run the UI service in Docker to support cross-host access. Click to view the guide on [running the sponge UI service in Docker](https://github.com/go-dev-frame/sponge/blob/main/assets/install-en.md#Docker%E7%8E%AF%E5%A2%83).
|
||||
|
||||
<br>
|
||||
|
||||
|
@ -126,11 +126,11 @@ Sponge has built-in rich features and components (for on-demand use):
|
|||
|
||||
<br>
|
||||
|
||||
### Generates Code Framework
|
||||
### Code Generation Engine
|
||||
|
||||
Sponge supports generating code using both built-in templates and custom templates, as shown in the diagrams below.
|
||||
The code generation engine of sponge supports two methods for generating the required project code: **built-in templates** and **custom templates**. Below are the framework diagrams for both approaches.
|
||||
|
||||
1. The code generation framework based on Sponge's built-in templates is shown below. There are two approaches: SQL and Protobuf.
|
||||
1. The framework for code generation based on built-in templates in sponge is shown below, supporting both SQL and Protobuf formats.
|
||||
|
||||
<p align="center">
|
||||
<img width="1500px" src="https://raw.githubusercontent.com/go-dev-frame/sponge/main/assets/sponge-framework.png">
|
||||
|
@ -138,7 +138,7 @@ Sponge supports generating code using both built-in templates and custom templat
|
|||
|
||||
<br>
|
||||
|
||||
2. The code generation framework based on custom templates is shown below. There are three approaches: JSON, SQL, and Protobuf.
|
||||
2. The framework for code generation based on custom templates in sponge is shown below, supporting JSON, SQL, and Protobuf formats.
|
||||
|
||||
<p align="center">
|
||||
<img width="1200px" src="https://raw.githubusercontent.com/go-dev-frame/sponge/main/assets/template-framework.png">
|
||||
|
|
|
@ -46,7 +46,7 @@ sponge 适用于快速开发各种高性能后端服务,包括但不限于:
|
|||
5. **AI 助手生成业务逻辑实现代码**
|
||||
sponge 内置了AI助手(DeepSeek 或 ChatGPT),两者优势互补,形成一套完整的高效开发解决方案:
|
||||
- **Sponge**:负责基础设施代码生成(服务框架、CRUD API 接口、缺少业务逻辑实现的自定义 API 接口等)。
|
||||
- **DeepSeek 或 ChatGPT**:专注业务逻辑实现(表结构 DDL 设计、自定义 API 接口定义、业务逻辑实现代码)。
|
||||
- **AI助手**:专注业务逻辑实现(表结构 DDL 设计、自定义 API 接口定义、业务逻辑实现代码)。
|
||||
|
||||
<br>
|
||||
|
||||
|
@ -110,11 +110,11 @@ sponge 内置了丰富的功能或组件(按需使用):
|
|||
|
||||
<br>
|
||||
|
||||
### 生成代码的框架
|
||||
### 代码生成引擎
|
||||
|
||||
sponge 支持基于自带模板和自定义模板两种方式生成你的项目所需的代码,下面是两种生成代码的框架图。
|
||||
sponge 的代码生成引擎支持**内置模板**和**自定义模板**两种方式生成项目所需的代码,下面是两种生成代码的框架图。
|
||||
|
||||
1. sponge 基于自带模板生成代码框架如下图所示,支持 sql 和 protobuf 两种方式。
|
||||
1. sponge 基于内置模板生成代码框架如下图所示,支持 sql 和 protobuf 两种方式。
|
||||
|
||||
<p align="center">
|
||||
<img width="1500px" src="https://raw.githubusercontent.com/go-dev-frame/sponge/main/assets/sponge-framework.png">
|
||||
|
|
2
go.mod
2
go.mod
|
@ -7,7 +7,7 @@ require (
|
|||
github.com/IBM/sarama v1.43.2
|
||||
github.com/alicebob/miniredis/v2 v2.23.0
|
||||
github.com/bojand/ghz v0.117.0
|
||||
github.com/dgraph-io/ristretto v0.1.1
|
||||
github.com/dgraph-io/ristretto v0.2.0
|
||||
github.com/fatih/color v1.13.0
|
||||
github.com/felixge/fgprof v0.9.3
|
||||
github.com/fsnotify/fsnotify v1.5.4
|
||||
|
|
2
go.sum
2
go.sum
|
@ -146,6 +146,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
|||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8=
|
||||
github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA=
|
||||
github.com/dgraph-io/ristretto v0.2.0 h1:XAfl+7cmoUDWW/2Lx8TGZQjjxIQ2Ley9DSf52dru4WE=
|
||||
github.com/dgraph-io/ristretto v0.2.0/go.mod h1:8uBHCU/PBV4Ag0CJrP47b9Ofby5dqWNh4FicAdoqFNU=
|
||||
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=
|
||||
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
|
|
|
@ -23,7 +23,9 @@ func Parse(configFile string, obj interface{}, reloads ...func()) error {
|
|||
|
||||
filePathStr, filename := filepath.Split(confFileAbs)
|
||||
ext := strings.TrimLeft(path.Ext(filename), ".")
|
||||
filename = strings.ReplaceAll(filename, "."+ext, "") // excluding suffix names
|
||||
if ext != "toml" {
|
||||
filename = strings.ReplaceAll(filename, "."+ext, "") // excluding suffix names
|
||||
}
|
||||
|
||||
viper.AddConfigPath(filePathStr) // path
|
||||
viper.SetConfigName(filename) // file name
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## dlock
|
||||
|
||||
`dlock` is a distributed lock library based on [**redsync**](https://github.com/go-redsync/redsync) and [**etcd**](https://github.com/etcd-io/etcd). It provides a simple and easy-to-use API for acquiring and releasing locks.
|
||||
`dlock` is a distributed lock library based on [**redsync**](https://github.com/go-redsync/redsync) and [**etcd**](https://github.com/etcd-io/etcd). It provides a simple and easy-to-use interface for acquiring and releasing locks.
|
||||
|
||||
<br>
|
||||
|
||||
|
@ -38,31 +38,37 @@ func main() {
|
|||
{
|
||||
ok, err := locker.TryLock(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to TryLock", err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fmt.Println("failed to acquire lock")
|
||||
fmt.Println("failed to lock")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := locker.Unlock(ctx); err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to unlock", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
// do something here
|
||||
// business logic requiring lock protection is executed here
|
||||
// ......
|
||||
}
|
||||
|
||||
// case 2: lock acquired, block until released, timeout, ctx error
|
||||
{
|
||||
if err := locker.Lock(ctx); err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to lock")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := locker.Unlock(ctx); err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to unlock", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
// do something here
|
||||
// business logic requiring lock protection is executed here
|
||||
// ......
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -100,31 +106,37 @@ func main() {
|
|||
{
|
||||
ok, err := locker.TryLock(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to TryLock", err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fmt.Println("failed to acquire lock")
|
||||
fmt.Println("failed to lock")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := locker.Unlock(ctx); err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to unlock", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
// do something here
|
||||
// business logic requiring lock protection is executed here
|
||||
// ......
|
||||
}
|
||||
|
||||
// case 2: lock acquired, block until released, timeout, ctx error
|
||||
{
|
||||
if err := locker.Lock(ctx); err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to lock", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := locker.Unlock(ctx); err != nil {
|
||||
panic(err)
|
||||
fmt.Println("failed to unlock", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
// do something here
|
||||
// business logic requiring lock protection is executed here
|
||||
// ......
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
## middleware
|
||||
|
||||
Gin middleware plugin.
|
||||
Common gin middleware libraries.
|
||||
|
||||
<br>
|
||||
|
||||
## Example of use
|
||||
|
||||
### logging middleware
|
||||
### Logging middleware
|
||||
|
||||
You can set the maximum length for printing, add a request id field, ignore print path, customize [zap](go.uber.org/zap) log.
|
||||
|
||||
|
@ -43,7 +43,7 @@ You can set the maximum length for printing, add a request id field, ignore prin
|
|||
|
||||
<br>
|
||||
|
||||
### rate limiter middleware
|
||||
### Rate limiter middleware
|
||||
|
||||
Adaptive flow limitation based on hardware resources.
|
||||
|
||||
|
@ -82,7 +82,7 @@ Adaptive flow limitation based on hardware resources.
|
|||
|
||||
<br>
|
||||
|
||||
### jwt authorization middleware
|
||||
### JWT authorization middleware
|
||||
|
||||
JWT supports two verification methods:
|
||||
|
||||
|
@ -102,18 +102,15 @@ func main() {
|
|||
|
||||
// Choose to use one of the following 4 authorization
|
||||
|
||||
// case 1: default authorization
|
||||
r.GET("/user/:id", middleware.Auth(), h.GetByID)
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithDefaultVerify()), h.GetByID) // equivalent to middleware.Auth()
|
||||
// Case 1: default authorization
|
||||
r.GET("/user/:id", middleware.Auth(), GetByID) // equivalent to middleware.Auth(middleware.WithDefaultVerify())
|
||||
// default authorization with extra verification
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithDefaultVerify(extraDefaultVerifyFn)), GetByID)
|
||||
|
||||
// case 2: default authorization with extra verification
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithDefaultVerify(extraDefaultVerifyFn)), h.GetByID)
|
||||
|
||||
// case 3: custom authorization
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithCustomVerify()), h.GetByID)
|
||||
|
||||
// case 4: custom authorization with extra verification
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithCustomVerify(extraCustomVerifyFn)), h.GetByID)
|
||||
// Case 2: custom authorization
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithCustomVerify()), GetByID)
|
||||
// custom authorization with extra verification
|
||||
r.GET("/user/:id", middleware.Auth(middleware.WithCustomVerify(extraCustomVerifyFn)), GetByID)
|
||||
|
||||
r.Run(serverAddr)
|
||||
}
|
||||
|
@ -121,17 +118,28 @@ func main() {
|
|||
func Login(c *gin.Context) {
|
||||
// ......
|
||||
|
||||
// case 1: generate token with default fields
|
||||
// Case 1: generate token with default fields
|
||||
token, err := jwt.GenerateToken("123", "admin")
|
||||
|
||||
// case 2: generate token with custom fields
|
||||
// Case 2: generate token with custom fields
|
||||
fields := jwt.KV{"id": uint64(100), "name": "tom", "age": 10}
|
||||
token, err := jwt.GenerateCustomToken(fields)
|
||||
|
||||
// ......
|
||||
}
|
||||
|
||||
func GetByID(c *gin.Context) {}
|
||||
func GetByID(c *gin.Context) {
|
||||
// Case 1: default authorization
|
||||
uid := c.MustGet("uid").(string)
|
||||
name := c.MustGet("name").(string)
|
||||
|
||||
// Case 2: custom authorization
|
||||
// Get information according to key-value pairs set in extraCustomVerifyFn function.
|
||||
// id, exists := c.Get("id")
|
||||
// name, exists := c.Get("name")
|
||||
|
||||
// ......
|
||||
}
|
||||
|
||||
func extraDefaultVerifyFn(claims *jwt.Claims, tokenTail10 string, c *gin.Context) error {
|
||||
// In addition to jwt certification, additional checks can be customized here.
|
||||
|
@ -162,13 +170,17 @@ func extraCustomVerifyFn(claims *jwt.CustomClaims, tokenTail10 string, c *gin.Co
|
|||
// age, exist := claims.GetInt("age")
|
||||
// if !exist || age != fields["age"].(int) { return err }
|
||||
|
||||
// set key-value pairs in gin.Context
|
||||
// c.Set("uid", id)
|
||||
// c.Set("name", name)
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
### tracing middleware
|
||||
### Tracing middleware
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/tracer"
|
||||
|
|
|
@ -138,10 +138,9 @@ func Auth(opts ...AuthOption) gin.HandlerFunc {
|
|||
c.Abort()
|
||||
return
|
||||
}
|
||||
} else {
|
||||
c.Set("uid", claims.UID)
|
||||
c.Set("name", claims.Name)
|
||||
}
|
||||
c.Set("uid", claims.UID)
|
||||
c.Set("name", claims.Name)
|
||||
}
|
||||
|
||||
c.Next()
|
||||
|
|
|
@ -11,61 +11,75 @@ package main
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-dev-frame/sponge/pkg/gin/validator"
|
||||
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-dev-frame/sponge/pkg/gin/response"
|
||||
|
||||
"user/docs" // docs is generated by Swag CLI, you have to import it.
|
||||
)
|
||||
|
||||
// @title serverNameExample api docs
|
||||
// @description http server api docs
|
||||
// @schemes http https
|
||||
// @version 2.0
|
||||
// @host localhost:8080
|
||||
// @securityDefinitions.apikey BearerAuth
|
||||
// @in header
|
||||
// @name Authorization
|
||||
// @description Type Bearer your-jwt-token to Value
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
binding.Validator = validator.Init()
|
||||
|
||||
|
||||
docs.SwaggerInfo.BasePath = ""
|
||||
// access path /swagger/index.html
|
||||
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
r.POST("/create_user", CreateUser)
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
|
||||
type createUserRequest struct {
|
||||
Name string `json:"name" form:"name" binding:"required"`
|
||||
Password string `json:"password" form:"password" binding:"required"`
|
||||
Age int `json:"age" form:"age" binding:"gte=0,lte=120"`
|
||||
Email string `json:"email" form:"email" binding:"email"`
|
||||
}
|
||||
|
||||
// Create user
|
||||
// @Summary create user
|
||||
// @Description submit information to create user
|
||||
// @Tags user
|
||||
// @accept json
|
||||
// @Produce json
|
||||
// @Param data body types.CreateUserRequest true "user information"
|
||||
// @Success 200 {object} types.CreateUserReply{}
|
||||
// @Router /api/v1/user [post]
|
||||
// @Security BearerAuth
|
||||
func CreateUser(c *gin.Context) {
|
||||
form := &createUserRequest{}
|
||||
form := &CreateUserRequest{}
|
||||
err := c.ShouldBindJSON(form)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"msg": "ok"})
|
||||
// create user logic...
|
||||
|
||||
response.Success(c, gin.H{"id": 123})
|
||||
}
|
||||
|
||||
type getUserRequest struct {
|
||||
Page int `json:"page" form:"page" binding:"gte=0"`
|
||||
Limit int `json:"limit" form:"limit" binding:"gte=1"`
|
||||
Sort string `json:"sort" form:"sort" binding:"-"`
|
||||
type CreateUserRequest struct {
|
||||
Name string `json:"name"`
|
||||
Password string `json:"password"`
|
||||
Age int `json:"age"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func GetUsers(c *gin.Context) {
|
||||
form := &getUserRequest{}
|
||||
err := c.ShouldBindQuery(form)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
users, err := getUsers(form)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"users": users})
|
||||
type CreateUserReply struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
ID uint64 `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func getUsers(req *getUserRequest) ([]User,error){}
|
||||
```
|
||||
|
||||
Test api with swagger:
|
||||
|
||||
1. install swag: `go install github.com/swaggo/swag/cmd/swag@latest`
|
||||
2. generate docs: `swag init`
|
||||
3. run server: `go run main.go`
|
||||
4. visit `http://localhost:8080/swagger/index.html` in your browser
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## validator
|
||||
|
||||
gin request parameter check library.
|
||||
`validator` is based on [validator](https://github.com/go-playground/validator) library. It provides request parameter validation for gin.
|
||||
|
||||
<br>
|
||||
|
||||
|
@ -22,6 +22,8 @@ func main() {
|
|||
r := gin.Default()
|
||||
binding.Validator = validator.Init()
|
||||
|
||||
r.POST("/create_user", CreateUser)
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
|
||||
|
@ -41,29 +43,4 @@ func CreateUser(c *gin.Context) {
|
|||
}
|
||||
c.JSON(http.StatusOK, gin.H{"msg": "ok"})
|
||||
}
|
||||
|
||||
type getUserRequest struct {
|
||||
Page int `json:"page" form:"page" binding:"gte=0"`
|
||||
Limit int `json:"limit" form:"limit" binding:"gte=1"`
|
||||
Sort string `json:"sort" form:"sort" binding:"-"`
|
||||
}
|
||||
|
||||
func GetUsers(c *gin.Context) {
|
||||
form := &getUserRequest{}
|
||||
err := c.ShouldBindQuery(form)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
users, err := getUsers(form)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"users": users})
|
||||
}
|
||||
|
||||
func getUsers(req *getUserRequest) ([]User,error){}
|
||||
```
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## gotest
|
||||
|
||||
gotest is a library that simulates the testing of cache, dao and handler.
|
||||
`gotest` is a library that simulates the testing of cache, dao and handler.
|
||||
|
||||
<br>
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## benchmark
|
||||
|
||||
Compression testing of rpc methods and generation of reported results.
|
||||
`benchmark` is a library that tests the performance of RPC methods and generates report results, it is based on the [ghz](https://github.com/bojand/ghz) library.
|
||||
|
||||
### Example of use
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## grpc client
|
||||
## gRPC client
|
||||
|
||||
Generic grpc client.
|
||||
`client` is a gRPC client library for Go. It provides a simple way to connect to a gRPC server and call its methods.
|
||||
|
||||
### Example of use
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## grpccli
|
||||
|
||||
grpc client with support for service discovery, logging, load balancing, trace, metrics, retries, circuit breaker.
|
||||
`grpccli` is Go's gRPC client library that supports for service discovery, logging, load balancing, trace, metrics, retries, circuit breaker.
|
||||
|
||||
### Example of use
|
||||
|
||||
|
|
|
@ -372,16 +372,14 @@ func getUnaryServerOptions() []grpc.ServerOption {
|
|||
interceptor.UnaryServerJwtAuth(
|
||||
// Choose to use one of the following 4 authorization
|
||||
|
||||
// case 1: default authorization
|
||||
// Case 1: default authorization
|
||||
// interceptor.WithDefaultVerify(), // can be ignored
|
||||
|
||||
// case 2: default authorization with extra verification
|
||||
// default authorization with extra verification
|
||||
// interceptor.WithDefaultVerify(extraDefaultVerifyFn),
|
||||
|
||||
// case 3: custom authorization
|
||||
// Case 2: custom authorization
|
||||
// interceptor.WithCustomVerify(),
|
||||
|
||||
// case 4: custom authorization with extra verification
|
||||
// custom authorization with extra verification
|
||||
// interceptor.WithCustomVerify(extraCustomVerifyFn),
|
||||
|
||||
// specify the gRPC API to ignore token verification(full path)
|
||||
|
@ -404,10 +402,10 @@ type user struct {
|
|||
func (s *user) Login(ctx context.Context, req *userV1.LoginRequest) (*userV1.LoginReply, error) {
|
||||
// check user and password success
|
||||
|
||||
// case 1: generate token with default fields
|
||||
// Case 1: default authorization
|
||||
token, err := jwt.GenerateToken("123", "admin")
|
||||
|
||||
// case 2: generate token with custom fields
|
||||
// Case 2: custom authorization
|
||||
fields := jwt.KV{"id": uint64(100), "name": "tom", "age": 10}
|
||||
token, err := jwt.GenerateCustomToken(fields)
|
||||
|
||||
|
@ -419,7 +417,13 @@ func (s *user) GetByID(ctx context.Context, req *userV1.GetUserByIDRequest) (*us
|
|||
// if token is valid, won't get here, because the interceptor has returned an error message
|
||||
|
||||
// if you want get jwt claims, you can use the following code
|
||||
// Case 1: default authorization
|
||||
claims, err := interceptor.GetJwtClaims(ctx)
|
||||
|
||||
// Case 2: custom authorization
|
||||
customClaims, err := interceptor.GetJwtCustomClaims(ctx)
|
||||
|
||||
// ......
|
||||
|
||||
return &userV1.GetUserByIDReply{},nil
|
||||
}
|
||||
|
|
|
@ -1,10 +1,14 @@
|
|||
## resolve
|
||||
|
||||
`resolve` is a library that grpc client-side load balancing policy.
|
||||
|
||||
### Example of use
|
||||
|
||||
#### grpc client
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/go-dev-frame/sponge/pkg/grpc/resolve"
|
||||
|
||||
func getDialOptions() []grpc.DialOption {
|
||||
var options []grpc.DialOption
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## grpc server
|
||||
|
||||
Generic grpc server.
|
||||
`server` is a gRPC server library for Go, it provides a simple way to create and run a gRPC server.
|
||||
|
||||
### Example of use
|
||||
|
||||
|
|
|
@ -1,11 +1,13 @@
|
|||
### httpcli
|
||||
|
||||
`httcli` is a simple HTTP request client, which only supports returning json format.
|
||||
`httcli` is a simple HTTP request client library, which only supports returning json format.
|
||||
|
||||
<br>
|
||||
|
||||
### Example of use
|
||||
|
||||
`Get`, `Delete`, `Post`, `Put`, `Patch` request example with params, headers, and body. There are two ways to request, the first is to call a method directly, and the second is to create a client using the `httpcli.New()` method and then call the corresponding method of the client.
|
||||
|
||||
#### Request way 1
|
||||
|
||||
```go
|
||||
|
@ -37,11 +39,11 @@
|
|||
// Post
|
||||
err = httpcli.Post(result, url, body)
|
||||
err = httpcli.Post(result, url, body, httpcli.WithParams(params))
|
||||
err = httpcli.Delete(result, httpcli.WithParams(params), httpcli.WithHeaders(headers))
|
||||
err = httpcli.Post(result, url, body, httpcli.WithParams(params), httpcli.WithHeaders(headers))
|
||||
// Put
|
||||
err := httpcli.Put(result, url, body)
|
||||
err = httpcli.Put(result, url, body)
|
||||
// Patch
|
||||
err := httpcli.Patch(result, url, body)
|
||||
err = httpcli.Patch(result, url, body)
|
||||
```
|
||||
|
||||
<br>
|
||||
|
@ -60,7 +62,7 @@ Get, Delete request example.
|
|||
cli := httpcli.New().SetURL(url).SetHeaders(headers).SetParams(params)
|
||||
|
||||
// Get
|
||||
resp, err := cli.GET()
|
||||
resp, err := cli.Get()
|
||||
// Delete
|
||||
// resp, err := cli.Delete()
|
||||
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
## jwt
|
||||
|
||||
Generate and parse token based on [jwt](https://github.com/golang-jwt/jwt) library.
|
||||
`jwt` is a library for generating and parsing token based on [jwt](https://github.com/golang-jwt/jwt).
|
||||
|
||||
<br>
|
||||
|
||||
## Example of use
|
||||
|
||||
Example 1: common fields jwt
|
||||
### Default jwt
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/jwt"
|
||||
|
@ -37,7 +37,7 @@ Example 1: common fields jwt
|
|||
|
||||
<br>
|
||||
|
||||
Example 2: custom fields jwt
|
||||
### Custom jwt
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/jwt"
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## jy2struct
|
||||
|
||||
A library for generating go struct code, supporting json and yaml.
|
||||
`jy2struct`is a library for generating go struct code, supporting json and yaml.
|
||||
|
||||
<br>
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## krand
|
||||
|
||||
Generate random strings, integers, floating point numbers.
|
||||
Generate random strings, integers, floating point numbers, and id.
|
||||
|
||||
<br>
|
||||
|
||||
|
@ -51,6 +51,8 @@ Generate random strings, integers, floating point numbers.
|
|||
|
||||
### Generate id
|
||||
|
||||
Generate an id that grows by datetime.
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/krand"
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## rabbitmq
|
||||
|
||||
rabbitmq library wrapped in [github.com/rabbitmq/amqp091-go](github.com/rabbitmq/amqp091-go), supports automatic reconnection and customized setting parameters, includes `direct`, `topic`, `fanout`, `headers`, `delayed message`, `publisher subscriber` a total of six message types, and dead letter is supported.
|
||||
`rabbitmq` is a rabbitmq client library based on [amqp091-go](https://github.com/rabbitmq/amqp091-go), supports automatic reconnection and customized setting parameters, includes `direct`, `topic`, `fanout`, `headers`, `delayed message`, `publisher subscriber` a total of six message types, and dead letter is supported.
|
||||
|
||||
### Example of use
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## replacer
|
||||
|
||||
A library of replacement file content, supports replacement of files in local directories and embedded directory files via embed.
|
||||
`replacer` is a library of replacement file content, supports replacement of files in local directories and embedded directory files via embed.
|
||||
|
||||
<br>
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## sgorm
|
||||
|
||||
`sgorm` is a library encapsulated on [gorm](gorm.io/gorm), and added features such as tracer, paging queries, etc.
|
||||
`sgorm` is a library encapsulated on [gorm](https://gorm.io/gorm), and added features such as tracer, paging queries, etc.
|
||||
|
||||
Support `mysql`, `postgresql`, `sqlite`.
|
||||
|
||||
|
|
Binary file not shown.
|
@ -6,7 +6,7 @@ Circuit Breaker for web middleware and rpc interceptor.
|
|||
|
||||
### Example of use
|
||||
|
||||
**gin circuit breaker middleware**
|
||||
#### Gin circuit breaker middleware
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/shield/circuitbreaker"
|
||||
|
@ -42,7 +42,7 @@ func CircuitBreaker(opts ...CircuitBreakerOption) gin.HandlerFunc {
|
|||
|
||||
<br>
|
||||
|
||||
**rpc server circuit breaker interceptor**
|
||||
#### gRPC server circuit breaker interceptor
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/shield/circuitbreaker"
|
||||
|
|
|
@ -6,7 +6,7 @@ Adaptive rate limit, only available for linux systems.
|
|||
|
||||
### Example of use
|
||||
|
||||
#### gin ratelimit middleware
|
||||
#### Gin ratelimit middleware
|
||||
|
||||
```go
|
||||
import (
|
||||
|
@ -40,7 +40,7 @@ func RateLimit(opts ...RateLimitOption) gin.HandlerFunc {
|
|||
|
||||
<br>
|
||||
|
||||
#### grpc ratelimit interceptor
|
||||
#### gRPC ratelimit interceptor
|
||||
|
||||
```go
|
||||
import (
|
||||
|
|
|
@ -1,59 +1,45 @@
|
|||
## sql2code
|
||||
|
||||
Generate code for different purposes according to sql, support generating json, gorm model, update parameter, request parameter code, sql can be obtained from parameter, file, db three ways, priority from high to low.
|
||||
`sql2code` is a code generation engine that generates CRUD code for model, dao, handler, service, protobuf based on sql and supports database types mysql, mongodb, postgresql, sqlite3.
|
||||
|
||||
<br>
|
||||
|
||||
### Example of use
|
||||
|
||||
Main setting parameters.
|
||||
|
||||
```go
|
||||
type Args struct {
|
||||
SQL string // DDL sql
|
||||
|
||||
DDLFile string // DDL file
|
||||
|
||||
DBDsn string // connecting to mysql's dsn
|
||||
DBTable string // table name
|
||||
|
||||
Package string // specify the package name (only valid for model types)
|
||||
GormType bool // gorm type
|
||||
JSONTag bool // does it include a json tag
|
||||
JSONNamedType int // json naming type, 0: consistent with the column name, other values indicate a hump
|
||||
IsEmbed bool // is gorm.Model embedded
|
||||
CodeType string // specify the different types of code to be generated, namely model (default), json, dao, handler, proto
|
||||
}
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
Generated code example.
|
||||
Generate code based on database table.
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/sql2code"
|
||||
|
||||
// generate gorm model code
|
||||
code, err := sql2code.GenerateOne(&sql2code.Args{
|
||||
SQL: sqlData, // source from sql text
|
||||
// DDLFile: "user.sql", // source from sql file
|
||||
// DBDsn: "root:123456@(127.0.0.1:3306)/account"
|
||||
// DBTable "user"
|
||||
GormType: true,
|
||||
JSONTag: true,
|
||||
IsEmbed: true,
|
||||
CodeType: "model"
|
||||
// generate model, dao, handler, service and protobuf code, supports database type: mysql, mongodb, postgres, sqlite3
|
||||
codes, err := sql2code.Generate(&sql2code.Args{
|
||||
DBDriver: "mysql",
|
||||
DBDsn: "root:123456@(127.0.0.1:3306)/account"
|
||||
DBTable "user"
|
||||
GormType: true,
|
||||
JSONTag: true,
|
||||
IsEmbed: true,
|
||||
IsExtendedAPI: false
|
||||
})
|
||||
|
||||
// generate json, model, dao, handler code
|
||||
codes, err := sql2code.Generate(&sql2code.Args{
|
||||
SQL: sqlData, // source from sql text
|
||||
// DDLFile: "user.sql", // source from sql file
|
||||
// DBDsn: "root:123456@(127.0.0.1:3306)/account"
|
||||
// DBTable "user"
|
||||
GormType: true,
|
||||
JSONTag: true,
|
||||
IsEmbed: true,
|
||||
CodeType: "dao"
|
||||
})
|
||||
// write code to file
|
||||
```
|
||||
|
||||
Generate table information based on database table, used for customized code generation.
|
||||
|
||||
```go
|
||||
import "github.com/go-dev-frame/sponge/pkg/sql2code"
|
||||
|
||||
// generate table information based on database table, supports database type: mysql, mongodb, postgres, sqlite3
|
||||
codes, err := sql2code.Generate(&sql2code.Args{
|
||||
DBDriver: "mysql",
|
||||
DBDsn: "root:123456@(127.0.0.1:3306)/account"
|
||||
DBTable "user"
|
||||
GormType: true,
|
||||
JSONTag: true,
|
||||
IsEmbed: true,
|
||||
IsExtendedAPI: true
|
||||
})
|
||||
|
||||
// generate customized code to file
|
||||
```
|
|
@ -1,6 +1,6 @@
|
|||
// Package sql2code provides for generating code for different purposes according to sql,
|
||||
// support generating json, gorm model, update parameter, request parameter code,
|
||||
// sql can be obtained from parameter, file, db three ways, priority from high to low.
|
||||
// Package sql2code is a code generation engine that generates CRUD code for model,
|
||||
// dao, handler, service, protobuf based on sql and supports database types mysql,
|
||||
// mongodb, postgresql, sqlite3.
|
||||
package sql2code
|
||||
|
||||
import (
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// AutoOpenBrowser auto open browser
|
||||
func AutoOpenBrowser(visitURL string) error {
|
||||
var cmd string
|
||||
var args []string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
cmd = "cmd"
|
||||
args = []string{"/c", "start"}
|
||||
case "darwin":
|
||||
cmd = "open"
|
||||
default: // "linux", "freebsd", "openbsd", "netbsd"
|
||||
cmd = "xdg-open"
|
||||
}
|
||||
|
||||
args = append(args, visitURL)
|
||||
return exec.Command(cmd, args...).Start()
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
## WebSocket
|
||||
|
||||
`ws` is based on the [github.com/gorilla/websocket](https://github.com/gorilla/websocket) library, support automatic client reconnection.
|
||||
`ws` is a websocket library based on [gorilla/websocket](https://github.com/gorilla/websocket), support automatic client reconnection.
|
||||
|
||||
<br>
|
||||
|
||||
|
|
Loading…
Reference in New Issue