You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.0 KiB

  1. package utils
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. "zinx/ziface"
  7. )
  8. /*
  9. 存储一切有关Zinx框架的全局参数供其他模块使用
  10. 一些参数也可以通过 用户根据 zinx.json来配置
  11. */
  12. type GlobalObj struct {
  13. /*
  14. Server
  15. */
  16. TcpServer ziface.IServer //当前Zinx的全局Server对象
  17. Host string //当前服务器主机IP
  18. TcpPort int //当前服务器主机监听端口号
  19. Name string //当前服务器名称
  20. /*
  21. Zinx
  22. */
  23. Version string //当前Zinx版本号
  24. MaxPacketSize uint32 //都需数据包的最大值
  25. MaxConn int //当前服务器主机允许的最大链接个数
  26. WorkerPoolSize uint32 //业务工作Worker池的数量
  27. MaxWorkerTaskLen uint32 //业务工作Worker对应负责的任务队列最大任务存储数量
  28. /*
  29. config file path
  30. */
  31. ConfFilePath string
  32. }
  33. /*
  34. 定义一个全局的对象
  35. */
  36. var GlobalObject *GlobalObj
  37. //判断一个文件是否存在
  38. func PathExists(path string) (bool, error) {
  39. _, err := os.Stat(path)
  40. if err == nil {
  41. return true, nil
  42. }
  43. if os.IsNotExist(err) {
  44. return false, nil
  45. }
  46. return false, err
  47. }
  48. //读取用户的配置文件
  49. func (g *GlobalObj) Reload() {
  50. if confFileExists, _ := PathExists(g.ConfFilePath); confFileExists != true {
  51. //fmt.Println("Config File ", g.ConfFilePath , " is not exist!!")
  52. return
  53. }
  54. data, err := ioutil.ReadFile(g.ConfFilePath)
  55. if err != nil {
  56. panic(err)
  57. }
  58. //将json数据解析到struct中
  59. //fmt.Printf("json :%s\n", data)
  60. err = json.Unmarshal(data, &GlobalObject)
  61. if err != nil {
  62. panic(err)
  63. }
  64. }
  65. /*
  66. 提供init方法默认加载
  67. */
  68. func init() {
  69. //初始化GlobalObject变量,设置一些默认值
  70. GlobalObject = &GlobalObj{
  71. Name: "ZinxServerApp",
  72. Version: "V0.4",
  73. TcpPort: 7777,
  74. Host: "0.0.0.0",
  75. MaxConn: 12000,
  76. MaxPacketSize: 4096,
  77. ConfFilePath: "conf/zinx.json",
  78. WorkerPoolSize: 10,
  79. MaxWorkerTaskLen: 1024,
  80. }
  81. //从配置文件中加载一些用户配置的参数
  82. GlobalObject.Reload()
  83. }