util.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package controller
  2. import (
  3. "net"
  4. "net/http"
  5. "strings"
  6. "x-ui/config"
  7. "x-ui/logger"
  8. "x-ui/web/entity"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func getRemoteIp(c *gin.Context) string {
  12. value := c.GetHeader("X-Real-IP")
  13. if value != "" {
  14. return value
  15. }
  16. value = c.GetHeader("X-Forwarded-For")
  17. if value != "" {
  18. ips := strings.Split(value, ",")
  19. return ips[0]
  20. }
  21. addr := c.Request.RemoteAddr
  22. ip, _, _ := net.SplitHostPort(addr)
  23. return ip
  24. }
  25. func jsonMsg(c *gin.Context, msg string, err error) {
  26. jsonMsgObj(c, msg, nil, err)
  27. }
  28. func jsonObj(c *gin.Context, obj interface{}, err error) {
  29. jsonMsgObj(c, "", obj, err)
  30. }
  31. func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
  32. m := entity.Msg{
  33. Obj: obj,
  34. }
  35. if err == nil {
  36. m.Success = true
  37. if msg != "" {
  38. m.Msg = msg + I18nWeb(c, "success")
  39. }
  40. } else {
  41. m.Success = false
  42. m.Msg = msg + I18nWeb(c, "fail") + ": " + err.Error()
  43. logger.Warning(msg+I18nWeb(c, "fail")+": ", err)
  44. }
  45. c.JSON(http.StatusOK, m)
  46. }
  47. func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) {
  48. c.JSON(statusCode, entity.Msg{
  49. Success: success,
  50. Msg: msg,
  51. })
  52. }
  53. func html(c *gin.Context, name string, title string, data gin.H) {
  54. if data == nil {
  55. data = gin.H{}
  56. }
  57. data["title"] = title
  58. host := c.GetHeader("X-Forwarded-Host")
  59. if host == "" {
  60. host = c.GetHeader("X-Real-IP")
  61. }
  62. if host == "" {
  63. var err error
  64. host, _, err = net.SplitHostPort(c.Request.Host)
  65. if err != nil {
  66. host = c.Request.Host
  67. }
  68. }
  69. data["host"] = host
  70. data["request_uri"] = c.Request.RequestURI
  71. data["base_path"] = c.GetString("base_path")
  72. c.HTML(http.StatusOK, name, getContext(data))
  73. }
  74. func getContext(h gin.H) gin.H {
  75. a := gin.H{
  76. "cur_ver": config.GetVersion(),
  77. }
  78. for key, value := range h {
  79. a[key] = value
  80. }
  81. return a
  82. }
  83. func isAjax(c *gin.Context) bool {
  84. return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
  85. }