util.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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-Forwarded-For")
  13. if value != "" {
  14. ips := strings.Split(value, ",")
  15. return ips[0]
  16. } else {
  17. addr := c.Request.RemoteAddr
  18. ip, _, _ := net.SplitHostPort(addr)
  19. return ip
  20. }
  21. }
  22. func jsonMsg(c *gin.Context, msg string, err error) {
  23. jsonMsgObj(c, msg, nil, err)
  24. }
  25. func jsonObj(c *gin.Context, obj interface{}, err error) {
  26. jsonMsgObj(c, "", obj, err)
  27. }
  28. func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
  29. m := entity.Msg{
  30. Obj: obj,
  31. }
  32. if err == nil {
  33. m.Success = true
  34. if msg != "" {
  35. m.Msg = msg + I18n(c, "success")
  36. }
  37. } else {
  38. m.Success = false
  39. m.Msg = msg + I18n(c, "fail") + ": " + err.Error()
  40. logger.Warning(msg+I18n(c, "fail")+": ", err)
  41. }
  42. c.JSON(http.StatusOK, m)
  43. }
  44. func pureJsonMsg(c *gin.Context, success bool, msg string) {
  45. if success {
  46. c.JSON(http.StatusOK, entity.Msg{
  47. Success: true,
  48. Msg: msg,
  49. })
  50. } else {
  51. c.JSON(http.StatusOK, entity.Msg{
  52. Success: false,
  53. Msg: msg,
  54. })
  55. }
  56. }
  57. func html(c *gin.Context, name string, title string, data gin.H) {
  58. if data == nil {
  59. data = gin.H{}
  60. }
  61. data["title"] = title
  62. data["host"] = strings.Split(c.Request.Host, ":")[0]
  63. data["request_uri"] = c.Request.RequestURI
  64. data["base_path"] = c.GetString("base_path")
  65. c.HTML(http.StatusOK, name, getContext(data))
  66. }
  67. func getContext(h gin.H) gin.H {
  68. a := gin.H{
  69. "cur_ver": config.GetVersion(),
  70. }
  71. for key, value := range h {
  72. a[key] = value
  73. }
  74. return a
  75. }
  76. func isAjax(c *gin.Context) bool {
  77. return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
  78. }