// @APIVersion 1.0.0
// @Title 认证中心、用户中心
// @Description token、用户、角色、权限
package routers
import (
"fmt"
"strings"
"zhsq_go/code"
"zhsq_go/user_center/controllers"
"zhsq_go/user_center/models"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/httplib"
)
func init() {
// 所有接口访问之前的过滤器
beego.InsertFilter("/*", beego.BeforeRouter, func(ctx *context.Context) {
names := beego.AppConfig.Strings("proxy::names")
for i := range names {
//如果是静态资源,直接放行
url := beego.AppConfig.String(fmt.Sprintf("proxy::%s_url", names[i]))
if strings.HasPrefix(ctx.Request.RequestURI, url) {
if strings.Contains(ctx.Request.RequestURI, "swagger") || strings.Contains(ctx.Request.RequestURI, "api-docs") {
host := beego.AppConfig.String(fmt.Sprintf("proxy::%s_host", names[i]))
request := httplib.Get(fmt.Sprintf("%s%v", host, ctx.Request.RequestURI))
con, _ := request.Bytes()
if strings.HasSuffix(ctx.Request.RequestURI, ".css") {
ctx.Output.Header("Content-Type", "text/css")
}
ctx.Output.Body(con)
return
}
}
}
// 校验Token是否有效
result, userId := models.FilterValidateToken(ctx)
if !result { //Token无效
message := code.ApiResult{Code: code.UNAUTHORIZED, Message: "Token 无效!"}
ctx.Output.JSON(message, false, false)
return
} else {
//判断用户的请求
if strings.HasPrefix(ctx.Request.RequestURI, "/api/user-center") { //用户中心
// fmt.Println("userId :", userId)
ctx.Input.SetData("userId", userId)
} else {
for i := range names {
//实现代理
url := beego.AppConfig.String(fmt.Sprintf("proxy::%s_url", names[i]))
if strings.HasPrefix(ctx.Request.RequestURI, url) {
// fmt.Println("其他模块接口")
host := beego.AppConfig.String(fmt.Sprintf("proxy::%s_host", names[i]))
// 请求方式
method := ctx.Request.Method
// 请求路径
url := ctx.Request.RequestURI
var req *httplib.BeegoHTTPRequest
uri := fmt.Sprintf("%s%v", host, url)
// fmt.Println("请求地址:", uri, " 请求方式:", method)
if method == "POST" {
req = httplib.Post(uri)
// Post 请求参数
req.Body(ctx.Input.RequestBody)
} else if method == "GET" {
req = httplib.Get(uri)
}
req.Param("userId", userId)
req.Header("Content-Type", "application/json")
response, _ := req.Response()
// fmt.Println("response.Status :", response.Status)
if strings.Contains(response.Status, "200") {
con, _ := req.String()
ctx.WriteString(con)
} else {
ctx.Output.JSON(code.ApiResult{Code: code.FAILED, Message: "操作失败!"}, false, false)
}
}
}
}
}
})
ns := beego.NewNamespace("/api/user-center",
beego.NSNamespace("/token",
beego.NSInclude(
&controllers.TokenController{},
),
),
beego.NSNamespace("/user",
beego.NSInclude(
&controllers.UserController{},
),
),
)
beego.AddNamespace(ns)
}
appname = user_center
httpaddr = 192.168.2.83
httpport = 80
runmode = dev
autorender = false
copyrequestbody = true
EnableDocs = true
[ignored]
url=/token/authorize;/token/verification;/api/property/company/list
[proxy]
names=profit;property
profit_host=http://127.0.0.1:8081
profit_url=/api/profit
profit_language=golang
property_host=http://127.0.0.1:8090
property_url=/api/property
property_language=java