util.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 + I18nWeb(c, "success")
  36. }
  37. } else {
  38. m.Success = false
  39. m.Msg = msg + I18nWeb(c, "fail") + ": " + err.Error()
  40. logger.Warning(msg+I18nWeb(c, "fail")+": ", err)
  41. }
  42. c.JSON(http.StatusOK, m)
  43. }
  44. func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) {
  45. c.JSON(statusCode, entity.Msg{
  46. Success: success,
  47. Msg: msg,
  48. })
  49. }
  50. func html(c *gin.Context, name string, title string, data gin.H) {
  51. if data == nil {
  52. data = gin.H{}
  53. }
  54. data["title"] = title
  55. data["host"] = strings.Split(c.Request.Host, ":")[0]
  56. data["request_uri"] = c.Request.RequestURI
  57. data["base_path"] = c.GetString("base_path")
  58. c.HTML(http.StatusOK, name, getContext(data))
  59. }
  60. func getContext(h gin.H) gin.H {
  61. a := gin.H{
  62. "cur_ver": config.GetVersion(),
  63. }
  64. for key, value := range h {
  65. a[key] = value
  66. }
  67. return a
  68. }
  69. func isAjax(c *gin.Context) bool {
  70. return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
  71. }