router.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package boot
  2. import (
  3. "github.com/goflyfox/gtoken/gtoken"
  4. "github.com/gogf/gf/frame/g"
  5. "github.com/gogf/gf/net/ghttp"
  6. "github.com/gogf/gf/os/glog"
  7. )
  8. /*
  9. 绑定业务路由
  10. */
  11. func bindRouter() {
  12. s := g.Server()
  13. // 调试路由
  14. s.BindHandler("/hello", func(r *ghttp.Request) {
  15. r.Response.WriteJson(gtoken.Succ("hello"))
  16. })
  17. s.BindHandler("/system/user", func(r *ghttp.Request) {
  18. r.Response.WriteJson(gtoken.Succ("system user"))
  19. })
  20. loginFunc := Login
  21. // 启动gtoken
  22. gtoken := &gtoken.GfToken{
  23. //Timeout: 10 * 1000,
  24. CacheMode: g.Config().GetInt8("cache-mode"),
  25. LoginPath: "/login",
  26. LoginBeforeFunc: loginFunc,
  27. LogoutPath: "/user/logout",
  28. AuthPaths: g.SliceStr{"/user/*", "/system/*"},
  29. }
  30. gtoken.Start()
  31. }
  32. /*
  33. 统一路由注册
  34. */
  35. func initRouter() {
  36. s := g.Server()
  37. // 绑定路由
  38. bindRouter()
  39. // 首页
  40. s.BindHandler("/", func(r *ghttp.Request) {
  41. content, err := g.View().Parse("index.html", map[string]interface{}{
  42. "id": 1,
  43. "name": "GTOKEN",
  44. "title": g.Config().GetString("setting.title"),
  45. })
  46. if err != nil {
  47. glog.Error(err)
  48. }
  49. r.Response.Write(content)
  50. })
  51. // 某些浏览器直接请求favicon.ico文件,特别是产生404时
  52. s.SetRewrite("/favicon.ico", "/resource/image/favicon.ico")
  53. }
  54. func Login(r *ghttp.Request) (string, interface{}) {
  55. username := r.GetPostString("username")
  56. passwd := r.GetPostString("passwd")
  57. if username == "" || passwd == "" {
  58. r.Response.WriteJson(gtoken.Fail("账号或密码错误."))
  59. r.ExitAll()
  60. }
  61. return username, ""
  62. }