Add go http client
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package midware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/opentdp/wechat-rest/args"
|
||||
)
|
||||
|
||||
func AuthGuard(c *gin.Context) {
|
||||
|
||||
token := ""
|
||||
|
||||
authcode := c.GetHeader("Authorization")
|
||||
parts := strings.SplitN(authcode, " ", 2)
|
||||
if len(parts) == 2 && parts[0] == "Bearer" {
|
||||
token = parts[1]
|
||||
}
|
||||
|
||||
if token != args.Httpd.Token {
|
||||
c.Set("Error", gin.H{"Code": 401, "Message": "未授权的操作"})
|
||||
c.Set("ExitCode", 401)
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package midware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 获取错误代码
|
||||
|
||||
func exitCode(c *gin.Context, code int) int {
|
||||
|
||||
if code := c.GetInt("ExitCode"); code > 100 {
|
||||
return code
|
||||
}
|
||||
|
||||
return code
|
||||
|
||||
}
|
||||
|
||||
// 创建错误实例
|
||||
|
||||
func newError(data any) error {
|
||||
|
||||
if err, ok := data.(error); ok {
|
||||
return err
|
||||
}
|
||||
|
||||
if err, ok := data.(string); ok {
|
||||
return errors.New(err)
|
||||
}
|
||||
|
||||
return errors.New("未知错误")
|
||||
|
||||
}
|
||||
|
||||
// 构造错误信息
|
||||
|
||||
func newErrorMessage(data any) gin.H {
|
||||
|
||||
if err, ok := data.(error); ok {
|
||||
return gin.H{"Error": gin.H{"Message": err.Error()}}
|
||||
}
|
||||
|
||||
if err, ok := data.(string); ok {
|
||||
return gin.H{"Error": gin.H{"Message": err}}
|
||||
}
|
||||
|
||||
return gin.H{"Error": data}
|
||||
|
||||
}
|
||||
|
||||
// 构造结构数据
|
||||
|
||||
func newPayload(data any, msg, token string) gin.H {
|
||||
|
||||
payload := gin.H{"Payload": data}
|
||||
|
||||
if msg != "" {
|
||||
payload["Message"] = msg
|
||||
}
|
||||
|
||||
if token != "" {
|
||||
payload["Token"] = token
|
||||
}
|
||||
|
||||
return payload
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package midware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func OutputHandle(c *gin.Context) {
|
||||
|
||||
c.Next()
|
||||
|
||||
// 输出错误信息
|
||||
|
||||
if err, exists := c.Get("Error"); exists {
|
||||
c.AbortWithStatusJSON(exitCode(c, 400), newErrorMessage(err))
|
||||
return
|
||||
}
|
||||
|
||||
// 输出请求结果
|
||||
|
||||
msg := c.GetString("Message")
|
||||
|
||||
if res, exists := c.Get("Payload"); exists || msg != "" {
|
||||
data := newPayload(res, msg, c.GetString("JwtToken"))
|
||||
c.AbortWithStatusJSON(exitCode(c, 200), data)
|
||||
return
|
||||
}
|
||||
|
||||
// 输出HTML内容
|
||||
|
||||
if htm := c.GetString("HTML"); htm != "" {
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
c.String(200, htm)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 捕获异常返回
|
||||
|
||||
c.AbortWithStatusJSON(500, newErrorMessage("内部错误"))
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user