59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"sundynix-micro-go/app/gateway/internal/config"
|
|
"sundynix-micro-go/app/gateway/internal/handler"
|
|
"sundynix-micro-go/app/gateway/internal/middleware"
|
|
|
|
"github.com/zeromicro/go-zero/core/conf"
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
var configFile = flag.String("f", "etc/gateway.yaml", "the config file")
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
|
|
var c config.Config
|
|
conf.MustLoad(*configFile, &c)
|
|
|
|
// 构建反向代理路由器
|
|
proxyRouter := handler.NewProxyRouter(c.Upstreams)
|
|
|
|
// 构建请求处理链
|
|
var finalHandler http.Handler = proxyRouter
|
|
|
|
// 注入 CORS 中间件
|
|
if c.Cors.Enable {
|
|
corsMiddleware := middleware.NewCorsMiddleware(c.Cors.AllowOrigins, c.Cors.AllowMethods, c.Cors.AllowHeaders)
|
|
finalHandler = http.HandlerFunc(corsMiddleware.Handle(func(w http.ResponseWriter, r *http.Request) {
|
|
proxyRouter.ServeHTTP(w, r)
|
|
}))
|
|
}
|
|
|
|
// 健康检查
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
fmt.Fprintf(w, `{"code":200,"msg":"gateway is healthy","upstreams":%d}`, len(c.Upstreams))
|
|
})
|
|
mux.Handle("/", finalHandler)
|
|
|
|
addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
|
|
logx.Infof("===== Sundynix Gateway 启动 =====")
|
|
logx.Infof("监听地址: %s", addr)
|
|
logx.Infof("路由数量: %d", len(c.Upstreams))
|
|
for _, u := range c.Upstreams {
|
|
logx.Infof(" %s -> %s", u.Prefix, u.Target)
|
|
}
|
|
logx.Infof("================================")
|
|
|
|
if err := http.ListenAndServe(addr, mux); err != nil {
|
|
logx.Errorf("网关启动失败: %v", err)
|
|
}
|
|
}
|