util.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 getUriId(c *gin.Context) int64 {
  12. s := struct {
  13. Id int64 `uri:"id"`
  14. }{}
  15. _ = c.BindUri(&s)
  16. return s.Id
  17. }
  18. func getRemoteIp(c *gin.Context) string {
  19. value := c.GetHeader("X-Forwarded-For")
  20. if value != "" {
  21. ips := strings.Split(value, ",")
  22. return ips[0]
  23. } else {
  24. addr := c.Request.RemoteAddr
  25. ip, _, _ := net.SplitHostPort(addr)
  26. return ip
  27. }
  28. }
  29. func jsonMsg(c *gin.Context, msg string, err error) {
  30. jsonMsgObj(c, msg, nil, err)
  31. }
  32. func jsonObj(c *gin.Context, obj interface{}, err error) {
  33. jsonMsgObj(c, "", obj, err)
  34. }
  35. func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
  36. m := entity.Msg{
  37. Obj: obj,
  38. }
  39. if err == nil {
  40. m.Success = true
  41. if msg != "" {
  42. m.Msg = msg + I18n(c, "success")
  43. }
  44. } else {
  45. m.Success = false
  46. m.Msg = msg + I18n(c, "fail") + ": " + err.Error()
  47. logger.Warning(msg+I18n(c, "fail")+": ", err)
  48. }
  49. c.JSON(http.StatusOK, m)
  50. }
  51. func pureJsonMsg(c *gin.Context, success bool, msg string) {
  52. if success {
  53. c.JSON(http.StatusOK, entity.Msg{
  54. Success: true,
  55. Msg: msg,
  56. })
  57. } else {
  58. c.JSON(http.StatusOK, entity.Msg{
  59. Success: false,
  60. Msg: msg,
  61. })
  62. }
  63. }
  64. func html(c *gin.Context, name string, title string, data gin.H) {
  65. if data == nil {
  66. data = gin.H{}
  67. }
  68. data["title"] = title
  69. data["host"] = strings.Split(c.Request.Host, ":")[0]
  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. if h != nil {
  79. for key, value := range h {
  80. a[key] = value
  81. }
  82. }
  83. return a
  84. }
  85. func isAjax(c *gin.Context) bool {
  86. return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
  87. }