router.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "sparrow/pkg/generator"
  4. "sparrow/services/knowoapi/controllers"
  5. "sparrow/services/knowoapi/model"
  6. "sparrow/services/knowoapi/services"
  7. jwt "github.com/dgrijalva/jwt-go"
  8. jwtmiddleware "github.com/iris-contrib/middleware/jwt"
  9. "github.com/kataras/iris"
  10. "github.com/kataras/iris/mvc"
  11. )
  12. var router iris.Party
  13. func registerErrors(srv *iris.Application) {
  14. srv.OnAnyErrorCode(handleErrors)
  15. }
  16. func handleErrors(ctx iris.Context) {
  17. //logger.Default().Serve(ctx)
  18. err := controllers.ErrorResponse{
  19. Code: ctx.GetStatusCode(),
  20. Message: ctx.Values().GetStringDefault("reason", "未知错误"),
  21. }
  22. ctx.JSON(err)
  23. }
  24. // jwt 中间件配置
  25. func newJWThandle() func(ctx iris.Context) {
  26. jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
  27. ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  28. return []byte(model.SignedString), nil
  29. },
  30. ErrorHandler: func(ctx iris.Context, message string) {
  31. ctx.StatusCode(iris.StatusUnauthorized)
  32. ctx.Values().Set("reason", message)
  33. },
  34. SigningMethod: jwt.SigningMethodHS256,
  35. })
  36. return jwtHandler.Serve
  37. }
  38. // 请求路由
  39. func registerRouters(srv *iris.Application, models *model.All, gen *generator.KeyGenerator) {
  40. pService := services.NewProductService(models, gen)
  41. userService := services.NewUserService(models, gen)
  42. router = srv.Party("/api/v1")
  43. // 登陆,注册
  44. loginAPI := mvc.New(router.Party("/"))
  45. loginAPI.Register(userService).Handle(new(controllers.UserController))
  46. // 用户接口组
  47. userRouter := router.Party("/user")
  48. productAPI := mvc.New(userRouter.Party("/product", newJWThandle()))
  49. productAPI.Register(pService).Handle(new(controllers.ProductController))
  50. }