util.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package controller
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net"
  5. "net/http"
  6. "strings"
  7. "x-ui/config"
  8. "x-ui/logger"
  9. "x-ui/web/entity"
  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["request_uri"] = c.Request.RequestURI
  70. data["base_path"] = c.GetString("base_path")
  71. c.HTML(http.StatusOK, name, getContext(data))
  72. }
  73. func getContext(h gin.H) gin.H {
  74. a := gin.H{
  75. "cur_ver": config.GetVersion(),
  76. }
  77. if h != nil {
  78. for key, value := range h {
  79. a[key] = value
  80. }
  81. }
  82. return a
  83. }
  84. func isAjax(c *gin.Context) bool {
  85. return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
  86. }