main.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "app.yhyue.com/moapp/jybase/iputil"
  4. "bp.jydev.jianyu360.cn/BaseService/gateway/core/node"
  5. "bp.jydev.jianyu360.cn/BaseService/gateway_node/core/logs"
  6. "fmt"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/net/ghttp"
  9. "github.com/gogf/gf/v2/os/gcfg"
  10. "github.com/gogf/gf/v2/os/gctx"
  11. "github.com/gogf/guuid"
  12. "os"
  13. "os/signal"
  14. "syscall"
  15. "time"
  16. )
  17. func init() {
  18. g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetFileName("./etc/config.yaml") //设置配置文件
  19. logs.InitLogs()
  20. }
  21. func main() {
  22. var serverCode string = gcfg.Instance().MustGet(gctx.New(), "system.serverCode").String()
  23. var serverPort int = gcfg.Instance().MustGet(gctx.New(), "system.serverPort").Int()
  24. etcdNodes := gcfg.Instance().MustGet(gctx.New(), "system.etcdListen").Strings()
  25. server := g.Server()
  26. server.SetPort(serverPort)
  27. server.SetLogger(logs.GInfo)
  28. server.SetAccessLogEnabled(true)
  29. server.BindHandler("/k3s-demo/{page}", func(r *ghttp.Request) {
  30. content := fmt.Sprintf("%s %d", gcfg.Instance().MustGet(gctx.New(), "system.response").Strings(), time.Now().Unix())
  31. logs.GInfo.Info(gctx.New(), content)
  32. r.Response.WriteJson(map[string]interface{}{
  33. "Hostname": r.Request.Host,
  34. "Ip": r.GetRemoteIp(),
  35. "Method": r.Method,
  36. "ServerIp": iputil.InternalIp(),
  37. "uuid": guuid.New().String(),
  38. "content": content,
  39. })
  40. })
  41. //向网关注册表注册服务。此步骤应在服务启动后注册。服务有重试机制不受影响。
  42. //NewNode可传入etcd节点,默认http://127.0.0.1:2379
  43. closeNotify, err := node.NewNode(etcdNodes...).Register(serverCode, fmt.Sprintf("%d", serverPort))
  44. if err != nil {
  45. panic(err)
  46. }
  47. go func() {
  48. server.Run()
  49. }()
  50. //阻塞主进程,接受退出消息。关闭服务,从注册表中删除。
  51. //kill -9 信号接受不到,会有2~3秒延迟。服务有重试机制不受影响。
  52. quit := make(chan os.Signal, 1)
  53. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  54. <-quit
  55. closeNotify()
  56. }