@@ -74,14 +74,17 @@ Adaptive flow limitation based on hardware resources.
7474 import " github.com/zhufuyi/sponge/pkg/gin/middleware"
7575
7676 r := gin.Default ()
77- r.Use (middleware.CircuitBreaker ())
77+ r.Use (middleware.CircuitBreaker (
78+ // middleware.WithValidCode(http.StatusRequestTimeout), // add error code 408 for circuit breaker
79+ // middleware.WithDegradeHandler(handler), // add custom degrade handler
80+ ))
7881```
7982
8083<br >
8184
8285### jwt authorization middleware
8386
84- #### common authorization
87+ #### standard authorization
8588
8689``` go
8790import " github.com/zhufuyi/sponge/pkg/jwt"
@@ -91,8 +94,8 @@ func main() {
9194 r := gin.Default ()
9295
9396 r.POST (" /user/login" , Login)
94- r.GET (" /user/:id" , middleware.Auth (), h.GetByID ) // no verify field
95- // r.GET("/user/:id", middleware.Auth(middleware.WithVerify(adminVerify)), h.GetByID) // with verify field
97+ r.GET (" /user/:id" , middleware.Auth (), h.GetByID ) // do not get claims
98+ // r.GET("/user/:id", middleware.Auth(middleware.WithVerify(adminVerify)), h.GetByID) // get claims and check
9699
97100 r.Run (serverAddr)
98101}
@@ -127,38 +130,35 @@ func main() {
127130 r := gin.Default ()
128131
129132 r.POST (" /user/login" , Login)
130- r.GET (" /user/:id" , middleware.AuthCustom (verify), h.GetByID )
133+ r.GET (" /user/:id" , middleware.AuthCustom (verify), h.GetByID ) // get claims and check
131134
132135 r.Run (serverAddr)
133136}
134137
138+ // custom verify example
135139func verify (claims *jwt .CustomClaims , tokenTail10 string , c *gin .Context ) error {
136140 err := errors.New (" verify failed" )
137141
138- // token, fields := getToken(id) // from cache or database
142+ token , fields := getToken (id) // from cache or database
139143 // if tokenTail10 != token[len(token)-10:] { return err }
140-
141- id , exist := claims.Get (" id" )
142- if !exist {
143- return err
144- }
145- foo , exist := claims.Get (" foo" )
146- if !exist {
147- return err
148- }
149- if int (id.(float64 )) != fields[" id" ].(int ) ||
150- foo.(string ) != fields[" foo" ].(string ) {
151- return err
152- }
144+
145+ id , exist := claims.GetUint64 (" id" )
146+ if !exist || id != fields[" id" ].(uint64 ) { return err }
147+
148+ name , exist := claims.GetString (" name" )
149+ if !exist || name != fields[" name" ].(string ) { return err }
150+
151+ age , exist := claims.GetInt (" age" )
152+ if !exist || age != fields[" age" ].(int ) { return err }
153153
154154 return nil
155155}
156156
157157func Login (c *gin .Context ) {
158158 // generate token
159- fields := jwt.KV {" id" : 123 , " foo " : " bar " }
159+ fields := jwt.KV {" id" : uint64 ( 123 ) , " name " : " tom " , " age " : 10 }
160160 token , err := jwt.GenerateCustomToken (fields)
161- // save token end fields
161+ // save token and fields
162162}
163163```
164164
0 commit comments