router.go 1.5 KB

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