package middleware import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func TestRequireRoleKey(t *testing.T) { gin.SetMode(gin.TestMode) for _, test := range []struct { role string want int }{{role: "admin", want: http.StatusNoContent}, {role: "purchaser", want: http.StatusForbidden}} { engine := gin.New() engine.Use(func(c *gin.Context) { c.Set(jwt.JwtPayloadKey, jwt.MapClaims{"rolekey": test.role}) c.Next() }) engine.POST("/write", RequireRoleKey("admin"), func(c *gin.Context) { c.Status(http.StatusNoContent) }) response := httptest.NewRecorder() request := httptest.NewRequest(http.MethodPost, "/write", nil) engine.ServeHTTP(response, request) if response.Code != test.want { t.Fatalf("role %s got %d, want %d", test.role, response.Code, test.want) } } }