Files
s-ui/backend/api/utils.go
T
Alireza Ahmadi f40b27fd8b initial commit
2024-02-13 01:17:54 +01:00

81 lines
1.4 KiB
Go

package api
import (
"net"
"net/http"
"s-ui/logger"
"strings"
"github.com/gin-gonic/gin"
)
type Msg struct {
Success bool `json:"success"`
Msg string `json:"msg"`
Obj interface{} `json:"obj"`
}
func getRemoteIp(c *gin.Context) string {
value := c.GetHeader("X-Forwarded-For")
if value != "" {
ips := strings.Split(value, ",")
return ips[0]
} else {
addr := c.Request.RemoteAddr
ip, _, _ := net.SplitHostPort(addr)
return ip
}
}
func jsonMsg(c *gin.Context, msg string, err error) {
jsonMsgObj(c, msg, nil, err)
}
func jsonObj(c *gin.Context, obj interface{}, err error) {
jsonMsgObj(c, "", obj, err)
}
func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
m := Msg{
Obj: obj,
}
if err == nil {
m.Success = true
if msg != "" {
m.Msg = msg
}
} else {
m.Success = false
m.Msg = msg + err.Error()
logger.Warning("failed :", err)
}
c.JSON(http.StatusOK, m)
}
func pureJsonMsg(c *gin.Context, success bool, msg string) {
if success {
c.JSON(http.StatusOK, Msg{
Success: true,
Msg: msg,
})
} else {
c.JSON(http.StatusOK, Msg{
Success: false,
Msg: msg,
})
}
}
func checkLogin(c *gin.Context) {
if !IsLogin(c) {
if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
pureJsonMsg(c, false, "Not authorized")
} else {
c.Redirect(http.StatusTemporaryRedirect, "/login")
}
c.Abort()
} else {
c.Next()
}
}