🎨 完善网关

This commit is contained in:
李寻欢 2021-09-07 17:12:29 +08:00
parent 441132c04f
commit 5ebdb0b747
9 changed files with 49 additions and 78 deletions

18
.env Normal file
View File

@ -0,0 +1,18 @@
# Loki配置
LOKI_HOST=192.168.0.124
LOKI_PORT=3100
LOKI_SOURCE=goweb
# Nacos配置
NACOS_HOST=
NACOS_PORT=8848
# 命名空间用默认的public的话这儿就不写
NACOS_NAMESPACE=
# 除本文件以外的其他托管到Nacos的配置文件如果有多个则以半角分号`;`隔开 Ps. 后面可以把NACOS_*和系统启动相关的留着其他的全部托管到Nacos
NACOS_CONFIG_NAME=gateway.yml
# 系统启动配置
# Jaeger链路追踪
JAEGER_SERVER=192.168.0.124:6831
# 系统名称注册到Nacos需要比如支付系统可以写mb-pay
APP_NAME=goweb
# 系统运行端口
PORT=8888

View File

@ -2,7 +2,6 @@ package core
import (
"gopkg.in/yaml.v3"
"log"
)
type Config struct {
@ -10,6 +9,7 @@ type Config struct {
Routes []struct {
Path string `yaml:"path"`
Service string `yaml:"service"`
Enable bool `yaml:"enable"`
} `yaml:"routes"`
} `yaml:"gateway"`
}
@ -19,15 +19,15 @@ func ConfigChanged(data string) {
config := Config{}
err := yaml.Unmarshal([]byte(data), &config)
if err != nil {
log.Printf("解析配置文本失败: %v\n", err.Error())
Log.Error("解析配置文本失败: %v\n", err.Error())
return
}
rs := config.Gateway.Routes
var sma []serviceMap
for _, r := range rs {
item := NewServiceMapItem(r.Path, r.Service)
item := NewServiceMapItem(r.Path, r.Service, r.Enable)
sma = append(sma, item)
}
ServiceMap = sma
log.Println("配置文件解析完毕")
Log.Info("配置文件解析完毕")
}

View File

@ -3,8 +3,8 @@ package core
import (
"fmt"
"gateway/config"
"github.com/AllCute/loki-client-go/loki"
"github.com/go-kit/kit/log"
"github.com/grafana/loki-client-go/loki"
"github.com/prometheus/common/model"
"time"
)

View File

@ -7,7 +7,6 @@ import (
"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
"github.com/nacos-group/nacos-sdk-go/vo"
"io/ioutil"
"log"
"net/http"
"strings"
)
@ -27,24 +26,29 @@ func (n nacosClient) Remote(ctx *gin.Context) {
uri := ctx.Request.RequestURI
// 截取第二个/前面那一段
pathAry := strings.Split(uri, "/")
serviceName := ""
var service serviceMap
apiService := fmt.Sprintf("/%v", pathAry[1])
for _, s := range ServiceMap {
if s.Path != "" && s.Path == apiService {
serviceName = s.Service
service = s
break
}
}
if serviceName == "" {
if service.Service == "" {
ctx.String(http.StatusNotFound, "服务不可达")
return
}
if !service.Enable {
ctx.String(http.StatusServiceUnavailable, "系统维护中")
return
}
instance, err := n.client.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
ServiceName: serviceName,
ServiceName: service.Service,
})
if err != nil {
log.Printf("获取健康服务失败: %v\n", err.Error())
Log.Error("获取健康服务失败: %v\n", err.Error())
return
}
// 组装内部接口
@ -52,7 +56,7 @@ func (n nacosClient) Remote(ctx *gin.Context) {
// 创建Request对象
req, err := http.NewRequest(ctx.Request.Method, apiUrl, ctx.Request.Body)
if err != nil {
log.Printf("请求异常: %v\n", err)
Log.Error("请求异常: %v\n", err)
return
}
// 填充Form参数(大概率用不上)
@ -67,11 +71,11 @@ func (n nacosClient) Remote(ctx *gin.Context) {
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
log.Printf("请求异常: %v\n", err)
Log.Error("请求异常: %v\n", err)
return
}
// 返回结果到前端
sss, _ := ioutil.ReadAll(response.Body)
log.Println(string(sss))
Log.Debug(string(sss))
ctx.String(response.StatusCode, string(sss))
}

View File

@ -3,13 +3,14 @@ package core
type serviceMap struct {
Path string
Service string
Enable bool
}
func NewServiceMapItem(k, v string) serviceMap {
func NewServiceMapItem(k, v string, e bool) serviceMap {
//var sma []serviceMap
// 从Nacos读取规则
// gateway:
// - path: /user
// service: mb-user-service
return serviceMap{k, v}
return serviceMap{k, v, e}
}

51
go.mod
View File

@ -1,11 +1,10 @@
module gateway
go 1.17
go 1.16
require (
github.com/gin-gonic/gin v1.7.4
github.com/go-kit/kit v0.11.0
github.com/grafana/loki-client-go v0.0.0-20210114103019-6057f29bbf5b
github.com/nacos-group/nacos-sdk-go v1.0.8
github.com/opentracing/opentracing-go v1.2.0
github.com/prometheus/common v0.30.0
@ -15,53 +14,7 @@ require (
)
require (
github.com/AllCute/loki-client-go v1.0.0
github.com/HdrHistogram/hdrhistogram-go v1.1.2 // indirect
github.com/aliyun/alibaba-cloud-sdk-go v1.61.18 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-errors/errors v1.0.1 // indirect
github.com/go-logfmt/logfmt v0.5.0 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.2 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
github.com/json-iterator/go v1.1.11 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f // indirect
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mitchellh/mapstructure v1.2.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.11.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/procfs v0.6.0 // indirect
github.com/prometheus/prometheus v1.8.2-0.20201028100903-3245b3267b24 // indirect
github.com/toolkits/concurrent v0.0.0-20150624120057-a4371d70e3e3 // indirect
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b // indirect
golang.org/x/net v0.0.0-20210525063256-abc453219eb5 // indirect
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c // indirect
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 // indirect
golang.org/x/text v0.3.6 // indirect
google.golang.org/appengine v1.6.6 // indirect
google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c // indirect
google.golang.org/grpc v1.38.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
gopkg.in/ini.v1 v1.42.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

8
go.sum
View File

@ -35,6 +35,8 @@ cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RX
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
collectd.org v0.3.0/go.mod h1:A/8DzQBkF6abtvrT2j/AU/4tiBgJWYyh0y/oB/4MlWE=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/AllCute/loki-client-go v1.0.0 h1:ehEe1AXGgTmtgCWT6UJPAV8zkBcu2ZwBRBjZTUJ6KoQ=
github.com/AllCute/loki-client-go v1.0.0/go.mod h1:XVrqSRShylgfpsCL2uZT+rTQAaIl2x+cTwwREnNFfOo=
github.com/Azure/azure-sdk-for-go v46.4.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8=
github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
@ -400,8 +402,6 @@ github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51
github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/grafana/loki-client-go v0.0.0-20210114103019-6057f29bbf5b h1:1DUYqr/sahQqeqNg/j21MtwUp8OZiOZZrrkMX0qkfHY=
github.com/grafana/loki-client-go v0.0.0-20210114103019-6057f29bbf5b/go.mod h1:p/XbBGAyRtXz4hHjWQ8eHDxJiOCktJjqrpLh7EUvhDo=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
@ -659,7 +659,6 @@ github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeD
github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU=
github.com/prometheus/client_golang v1.6.0/go.mod h1:ZLOG9ck3JLRdB5MgO8f+lLTe83AXG6ro35rLTxvnIl4=
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
github.com/prometheus/client_golang v1.8.0/go.mod h1:O9VU6huf47PktckDQfMTX0Y8tY0/7TSWwj+ITvv0TnM=
github.com/prometheus/client_golang v1.11.0 h1:HNkLOAEQMIDv/K+04rukrLx6ch7msSRwf3/SASFAGtQ=
github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
@ -676,7 +675,6 @@ github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt2
github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4=
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
github.com/prometheus/common v0.14.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s=
github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s=
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
github.com/prometheus/common v0.30.0 h1:JEkYlQnpzrzQFxi6gnukFPdQ+ac82oRhzMcIduJu/Ug=
github.com/prometheus/common v0.30.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
@ -686,7 +684,6 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.0.11/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4=
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/prometheus/prometheus v1.8.2-0.20201028100903-3245b3267b24 h1:V/4Cj2GytqdqK7OMEz6c4LNjey3SNyfw3pg5jPKtJvQ=
@ -1005,7 +1002,6 @@ golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201008064518-c1f3e3309c71/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View File

@ -6,7 +6,6 @@ import (
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
"log"
)
// 初始化Nacos注册
@ -47,14 +46,14 @@ func initNacos() {
ServiceName: "gateway",
Ephemeral: true,
})
log.Println("Nacos注册结果: ", success)
core.Log.Debug("Nacos注册结果: %v", success)
if !success {
log.Fatal("服务注册失败,退出程序")
core.Log.Panic("服务注册失败,退出程序")
}
configClient, err := clients.NewConfigClient(configParam)
if err != nil {
log.Fatalf("创建配置连接失败: %v", err.Error())
core.Log.Error("创建配置连接失败: %v", err.Error())
}
_ = configClient.ListenConfig(vo.ConfigParam{
DataId: "gateway.yml",
@ -66,7 +65,7 @@ func initNacos() {
core.NacosClient = core.NewNacosClient(client, configClient)
configStr, err := configClient.GetConfig(vo.ConfigParam{DataId: "gateway.yml", Group: "DEFAULT_GROUP"})
if err != nil {
log.Panicf("读取配置文件错误: %v", err.Error())
core.Log.Panic("读取配置文件错误: %v", err.Error())
}
core.ConfigChanged(configStr)
}

View File

@ -1,9 +1,9 @@
package middleware
import (
"gateway/core"
"github.com/gin-gonic/gin"
"github.com/nacos-group/nacos-sdk-go/inner/uuid"
"log"
)
// GenRequestId 生成RequestId
@ -13,7 +13,7 @@ func GenRequestId() gin.HandlerFunc {
if requestId == "" {
u, err := uuid.NewV4()
if err != nil {
log.Printf("生成UUID错误: %v\n", err.Error())
core.Log.Error("生成UUID错误: %v\n", err.Error())
} else {
requestId = u.String()
}