Skip to content

Commit

Permalink
update doc
Browse files Browse the repository at this point in the history
  • Loading branch information
zhufuyi committed Oct 16, 2023
1 parent 678e262 commit b741a49
Show file tree
Hide file tree
Showing 19 changed files with 114 additions and 114 deletions.
4 changes: 1 addition & 3 deletions internal/handler/userExample.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,7 @@ func (h *userExampleHandler) List(c *gin.Context) {
userExamples, total, err := h.iDao.GetByColumns(ctx, &form.Params)
if err != nil {
logger.Error("GetByColumns error", logger.Err(err), logger.Any("form", form), middleware.GCtxRequestIDField(c))
//response.Output(c, ecode.InternalServerError.ToHTTPCode())
response.Output(c, ecode.Unauthorized.ToHTTPCode(), "详细错误信息")
response.Error(c, ecode.Unauthorized.WithOutMsg("错误简单描述"), "详细错误信息")
response.Output(c, ecode.InternalServerError.ToHTTPCode())
return
}

Expand Down
18 changes: 9 additions & 9 deletions pkg/conf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ Parsing yaml, json, toml configuration files to go struct.
import "github.com/zhufuyi/sponge/pkg/conf"

// Way 1: No listening profile
config := &App{}
err := conf.Parse("test.yml", config)
config := &App{}
err := conf.Parse("test.yml", config)

// Way 2: Enable listening profile
config := &App{}
fs := []func(){
func() {
fmt.Println("Listening for updates to the configuration file")
},
}
err := conf.Parse("test.yml", config, fs...)
config := &App{}
fs := []func(){
func() {
fmt.Println("Listening for updates to the configuration file")
},
}
err := conf.Parse("test.yml", config, fs...)
```
7 changes: 4 additions & 3 deletions pkg/consulcli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ Connect to the consul service client.
```go
import "github.com/zhufuyi/sponge/pkg/consulcli"

endpoints := []string{"192.168.3.37:2379"}
cli, err := consulcli.Init(endpoints,
endpoints := []string{"192.168.3.37:2379"}
cli, err := consulcli.Init(
endpoints,
WithConnectTimeout(time.Second*2),
// WithAuth("", ""),
// WithAutoSyncInterval(0),
// WithLog(zap.NewNop()),
)
)
```
10 changes: 5 additions & 5 deletions pkg/etcdcli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ Connect to the etcd service client.
```go
import "github.com/zhufuyi/sponge/pkg/etcdcli"

endpoints := []string{"192.168.3.37:2379"}
cli, err := etcdcli.Init(endpoints,
endpoints := []string{"192.168.3.37:2379"}
cli, err := etcdcli.Init(
endpoints,
WithConnectTimeout(time.Second*2),
// WithAuth("", ""),
// WithAutoSyncInterval(0),
// WithLog(zap.NewNop()),
)
)
// WithAuth("", ""),
)
```
67 changes: 34 additions & 33 deletions pkg/gin/middleware/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ You can set the maximum length for printing, add a request id field, ignore prin

r.Use(middleware.Logging(
middleware.WithMaxLen(400),
//WithRequestIDFromHeader(),
WithRequestIDFromContext(),
//WithRequestIDFromHeader(),
WithRequestIDFromContext(),
//middleware.WithIgnoreRoutes("/hello"),
))

Expand All @@ -44,7 +44,7 @@ You can set the maximum length for printing, add a request id field, ignore prin
Adaptive flow limitation based on hardware resources.

```go
r := gin.Default()
r := gin.Default()

// e.g. (1) use default
// r.Use(RateLimit())
Expand Down Expand Up @@ -79,24 +79,24 @@ func main() {
r := gin.Default()

r.POST("/user/login", Login)
r.GET("/user/:id", middleware.Auth(), h.GetByID)
// r.GET("/user/:id", middleware.Auth(middleware.WithVerify(verify)), userFun) // with verify
r.GET("/user/:id", middleware.Auth(), h.GetByID) // no verify field
// r.GET("/user/:id", middleware.Auth(middleware.WithVerify(adminVerify)), userFun) // with verify field

r.Run(serverAddr)
}

func verify(claims *jwt.Claims) error {
if claims.UID != "123" || claims.Role != "admin" {
func adminVerify(claims *jwt.Claims) error {
if claims.Role != "admin" {
return errors.New("verify failed")
}
return nil
}

func Login(c *gin.Context) {
// login success
// login success

// generate token
token, err := jwt.GenerateToken("123", "admin")
// generate token
token, err := jwt.GenerateToken("123", "admin")
// handle err
}
```
Expand All @@ -110,39 +110,40 @@ import "github.com/zhufuyi/sponge/pkg/jwt"
func main() {
r := gin.Default()

r.POST("/user/login", Login)
r.GET("/user/:id", middleware.AuthCustom(verifyCustom), userFun)
r.POST("/user/login", Login)
r.GET("/user/:id", middleware.AuthCustom(verify), userFun)

r.Run(serverAddr)
}

func verifyCustom(claims *jwt.CustomClaims) error {
err := errors.New("verify failed")
func verify(claims *jwt.CustomClaims) error {
err := errors.New("verify failed")

id, exist := claims.Get("id")
if !exist {
return err
}
foo, exist := claims.Get("foo")
if !exist {
return err
}
if int(id.(float64)) != fields["id"].(int) || foo.(string) != fields["foo"].(string) {
return err
}
id, exist := claims.Get("id")
if !exist {
return err
}
foo, exist := claims.Get("foo")
if !exist {
return err
}
if int(id.(float64)) != fields["id"].(int) || foo.(string) != fields["foo"].(string) {
return err
}

return nil
return nil
}

func Login(c *gin.Context) {
// login success

// generate token
fields := jwt.KV{"id": 123, "foo": "bar"}
token, err := jwt.GenerateCustomToken(fields)
// generate token
fields := jwt.KV{"id": 123, "foo": "bar"}
token, err := jwt.GenerateCustomToken(fields)
// handle err
}
```

<br>

### tracing middleware
Expand All @@ -164,10 +165,10 @@ func InitTrace(serviceName string) {
}

func NewRouter(
r := gin.Default()
r.Use(middleware.Tracing("your-service-name"))
r := gin.Default()
r.Use(middleware.Tracing("your-service-name"))

// ......
// ......
)

// if necessary, you can create a span in the program
Expand Down Expand Up @@ -200,6 +201,6 @@ func SpanDemo(serviceName string, spanName string, ctx context.Context) {
### Request id

```go
r := gin.Default()
r := gin.Default()
r.Use(RequestID())
```
5 changes: 3 additions & 2 deletions pkg/gin/middleware/metrics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ gin metrics library, collect five metrics, `uptime`, `http_request_count_total`,

<br>

### Usage
### Example of use

```go
import "github.com/zhufuyi/sponge/pkg/gin/middleware/metrics"

r := gin.Default()

r.Use(metrics.Metrics(r,
r.Use(metrics.Metrics(
r,
//metrics.WithMetricsPath("/demo/metrics"), // default is /metrics
metrics.WithIgnoreStatusCodes(http.StatusNotFound), // ignore status codes
//metrics.WithIgnoreRequestMethods(http.MethodHead), // ignore request methods
Expand Down
48 changes: 24 additions & 24 deletions pkg/gohttp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@ Get, Delete request example.
```go
import "github.com/zhufuyi/sponge/pkg/gohttp"

req := gohttp.Request{}
req.SetURL("http://localhost:8080/user")
req.SetHeaders(map[string]string{
"Authorization": "Bearer token",
})
req.SetParams(gohttp.KV{
"id": 123,
})

resp, err := req.GET()
// resp, err := req.Delete()

result := &gohttp.StdResult{} // other structures can be defined to receive data
err = resp.BindJSON(result)
req := gohttp.Request{}
req.SetURL("http://localhost:8080/user")
req.SetHeaders(map[string]string{
"Authorization": "Bearer token",
})
req.SetParams(gohttp.KV{
"id": 123,
})

resp, err := req.GET()
// resp, err := req.Delete()

result := &gohttp.StdResult{} // other structures can be defined to receive data
err = resp.BindJSON(result)
```

<br>
Expand All @@ -36,11 +36,11 @@ Post, Put, Patch request example.
```go
import "github.com/zhufuyi/sponge/pkg/gohttp"

req := gohttp.Request{}
req.SetURL("http://localhost:8080/user")
req.SetHeaders(map[string]string{
"Authorization": "Bearer token",
})
req := gohttp.Request{}
req.SetURL("http://localhost:8080/user")
req.SetHeaders(map[string]string{
"Authorization": "Bearer token",
})

// body is a structure
type User struct{
Expand All @@ -52,12 +52,12 @@ Post, Put, Patch request example.
// or body as json
// req.SetBody(`{"name":"foo", "email":"[email protected]"}`)

resp, err := req.Post()
// resp, err := req.Put()
// resp, err := req.Patch()
resp, err := req.Post()
// resp, err := req.Put()
// resp, err := req.Patch()

result := &gohttp.StdResult{} // other structures can be defined to receive data
err = resp.BindJSON(result)
result := &gohttp.StdResult{} // other structures can be defined to receive data
err = resp.BindJSON(result)
```

<br>
Expand Down
10 changes: 5 additions & 5 deletions pkg/grpc/interceptor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ func getDialOptions() []grpc.DialOption {
option := grpc.WithUnaryInterceptor(
grpc_middleware.ChainUnaryClient(
interceptor.UnaryClientRetry(
//middleware.WithRetryTimes(5), // modify the default number of retries to 3 by default
//middleware.WithRetryInterval(100*time.Millisecond), // modify the default retry interval, default 50 milliseconds
//middleware.WithRetryErrCodes(), // add trigger retry error code, default is codes.Internal, codes.DeadlineExceeded, codes.Unavailable
//middleware.WithRetryTimes(5), // modify the default number of retries to 3 by default
//middleware.WithRetryInterval(100*time.Millisecond), // modify the default retry interval, default 50 milliseconds
//middleware.WithRetryErrCodes(), // add trigger retry error code, default is codes.Internal, codes.DeadlineExceeded, codes.Unavailable
),
),
)
Expand Down Expand Up @@ -323,11 +323,11 @@ func getServerOptions() []grpc.ServerOption {

// generate forensic information authorization
func (a *Account) Register(ctx context.Context, req *serverNameV1.RegisterRequest) (*serverNameV1.RegisterReply, error) {
// ......
// ......
token, err := jwt.GenerateToken(uid)
// handle err
authorization = middleware.GetAuthorization(token)
// ......
// ......
}

// the client must pass in the authentication information via the context when calling the method, and the key name must be authorization
Expand Down
2 changes: 1 addition & 1 deletion pkg/grpc/metrics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func main() {
}

server := grpc.NewServer(getServerOptions()...)
serverNameV1.RegisterGreeterServer(server, &GreeterServer{})
serverNameV1.RegisterGreeterServer(server, &GreeterServer{})

// start metrics server, collect grpc metrics by default, turn on, go metrics
metrics.ServerHTTPService(":8283", server)
Expand Down
16 changes: 8 additions & 8 deletions pkg/jwt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ Example 1: common fields jwt
token, err := jwt.GenerateToken(uid)
// handle err

// parse token
// parse token
claims, err := jwt.ParseToken(token)
// handle err
// handle err

// verify
if claims.Uid != "123" ||claims.Role != "admin" {
Expand All @@ -52,17 +52,17 @@ Example 2: custom fields jwt

// generate token
token, err := jwt.GenerateCustomToken(uid)
// handle err
// handle err

// parse token
// parse token
claims, err := jwt.ParseCustomToken(token)
// handle err
// handle err

// verify
id, isExist1 := claims.Get("id")
foo, isExist2 := claims.Get("foo")
id, isExist1 := claims.Get("id")
foo, isExist2 := claims.Get("foo")
if !isExist1 || !isExist2 || int(id.(float64)) != fields["id"].(int) || foo.(string) != fields["foo"].(string) {
print("verify failed")
print("verify failed")
return
}
```
10 changes: 5 additions & 5 deletions pkg/mysql/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@
db, err := mysql.Init(dsn)

// (2) customised settings to connect to the database
db, err := mysql.Init(
dsn,
mysql.WithLogging(logger.Get()), // print log
mysql.WithLogRequestIDKey("request_id"), // print request_id
db, err := mysql.Init(
dsn,
mysql.WithLogging(logger.Get()), // print log
mysql.WithLogRequestIDKey("request_id"), // print request_id
mysql.WithMaxIdleConns(5),
mysql.WithMaxOpenConns(50),
mysql.WithConnMaxLifetime(time.Minute*3),
// mysql.WithSlowThreshold(time.Millisecond*100), // only print logs that take longer than 100 milliseconds to execute
// mysql.WithEnableTrace(), // enable tracing
// mysql.WithRWSeparation(SlavesDsn, MastersDsn...) // read-write separation
// mysql.WithGormPlugin(yourPlugin) // custom gorm plugin
)
)
```

<br>
Expand Down
2 changes: 1 addition & 1 deletion pkg/mysql/query/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func NewPage(page int, size int, columnNames string) *Page {
if page < 0 {
page = 0
}
if size > defaultMaxSize {
if size > defaultMaxSize || size < 1 {
size = defaultMaxSize
}

Expand Down
Loading

0 comments on commit b741a49

Please sign in to comment.