main.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package main
  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. func main() {
  9. g.Server().Run()
  10. }
  11. // 管理初始化顺序.
  12. func init() {
  13. initConfig()
  14. initRouter()
  15. }
  16. // 用于配置初始化.
  17. func initConfig() {
  18. glog.Info("########service start...")
  19. v := g.View()
  20. c := g.Config()
  21. s := g.Server()
  22. path := ""
  23. // 配置对象及视图对象配置
  24. c.AddPath(path + "config")
  25. v.SetDelimiters("${", "}")
  26. v.AddPath(path + "template")
  27. // glog配置
  28. logPath := c.GetString("log-path")
  29. glog.SetPath(logPath)
  30. glog.SetStdoutPrint(true)
  31. s.SetServerRoot("./public")
  32. s.SetNameToUriType(ghttp.URI_TYPE_ALLLOWER)
  33. s.SetLogPath(logPath)
  34. s.SetErrorLogEnabled(true)
  35. s.SetAccessLogEnabled(true)
  36. s.SetPort(c.GetInt("http-port"))
  37. glog.Info("########service finish.")
  38. }
  39. /*
  40. 绑定业务路由
  41. */
  42. func bindRouter() {
  43. s := g.Server()
  44. // 调试路由
  45. s.BindHandler("/hello", func(r *ghttp.Request) {
  46. r.Response.WriteJson(gtoken.Succ("hello"))
  47. })
  48. s.BindHandler("/system/user", func(r *ghttp.Request) {
  49. r.Response.WriteJson(gtoken.Succ("system user"))
  50. })
  51. loginFunc := Login
  52. // 启动gtoken
  53. gtoken := &gtoken.GfToken{
  54. //Timeout: 10 * 1000,
  55. CacheMode: g.Config().GetInt8("cache-mode"),
  56. LoginPath: "/login",
  57. LoginBeforeFunc: loginFunc,
  58. LogoutPath: "/user/logout",
  59. AuthPaths: g.SliceStr{"/user", "/system"},
  60. }
  61. gtoken.Start()
  62. }
  63. /*
  64. 统一路由注册
  65. */
  66. func initRouter() {
  67. s := g.Server()
  68. // 绑定路由
  69. bindRouter()
  70. // 首页
  71. s.BindHandler("/", func(r *ghttp.Request) {
  72. content, err := g.View().Parse("index.html", map[string]interface{}{
  73. "id": 1,
  74. "name": "GTOKEN",
  75. "title": g.Config().GetString("setting.title"),
  76. })
  77. if err != nil {
  78. glog.Error(err)
  79. }
  80. r.Response.Write(content)
  81. })
  82. // 某些浏览器直接请求favicon.ico文件,特别是产生404时
  83. s.SetRewrite("/favicon.ico", "/resource/image/favicon.ico")
  84. }
  85. func Login(r *ghttp.Request) (string, interface{}) {
  86. username := r.GetPostString("username")
  87. passwd := r.GetPostString("passwd")
  88. if username == "" || passwd == "" {
  89. r.Response.WriteJson(gtoken.Fail("账号或密码错误."))
  90. r.ExitAll()
  91. }
  92. return username, ""
  93. }