LingxinMeng 1 jaar geleden
bovenliggende
commit
3420495fa8

+ 0 - 0
amd64/kubernetes-scheduler/main/main.go → amd64/kubernetes-scheduler/main.go


+ 19 - 0
amd64/report-server/application.yaml

@@ -0,0 +1,19 @@
+application-name: report-server
+web:
+  port: 12345
+  route-prefix: /report-server
+  token: U9yKpD6kZZDDe4LFKK6myAxBUT1XRrDM
+  white-list:
+    - "/report-server/swagger"
+log:
+  dir: ./log/
+  prefix: report-server
+mysql:
+  ip: 36.110.106.156
+  port: 3306
+  username: root
+  password: 1qaz2wsx!
+  dbname: dataclosedloop
+  charset: utf8
+  sql-files-dir: D:\code\yuexin-platform\yuexin-pay\sql
+

+ 85 - 0
amd64/report-server/main.go

@@ -0,0 +1,85 @@
+package main
+
+import (
+	"cicv-data-closedloop/common/config/c_db"
+	"cicv-data-closedloop/common/config/c_log"
+	"cicv-data-closedloop/common/gin/handler"
+	"cicv-data-closedloop/common/gin/middleware"
+	_ "embed"
+	"github.com/gin-gonic/gin"
+	"gopkg.in/yaml.v3"
+	"os"
+)
+
+type ApplicationYamlStruct struct {
+	ApplicationName string `yaml:"application"`
+	Web             struct {
+		Port        string   `yaml:"port"`
+		RoutePrefix string   `yaml:"route-prefix"`
+		Token       string   `yaml:"token"`
+		WhiteList   []string `yaml:"white-list"`
+	} `yaml:"web"`
+	Log struct {
+		Dir    string `yaml:"dir"`
+		Prefix string `yaml:"prefix"`
+	} `yaml:"log"`
+	Mysql struct {
+		Ip       string `yaml:"ip"`
+		Port     string `yaml:"port"`
+		Username string `yaml:"username"`
+		Password string `yaml:"password"`
+		Dbname   string `yaml:"dbname"`
+		Charset  string `yaml:"charset"`
+	} `yaml:"mysql"`
+}
+
+var (
+	//go:embed application.yaml
+	applicationYamlBytes []byte
+	ApplicationYaml      ApplicationYamlStruct
+)
+
+func init() {
+	// 解析YAML内容
+	_ = yaml.Unmarshal(applicationYamlBytes, &ApplicationYaml)
+	c_log.InitLog(
+		ApplicationYaml.Log.Dir,
+		ApplicationYaml.Log.Prefix,
+	)
+	c_db.InitSqlxMysql(
+		ApplicationYaml.Mysql.Ip,
+		ApplicationYaml.Mysql.Port,
+		ApplicationYaml.Mysql.Username,
+		ApplicationYaml.Mysql.Password,
+		ApplicationYaml.Mysql.Dbname,
+		ApplicationYaml.Mysql.Charset,
+	)
+}
+
+// @title yuexin-pay系统接口文档
+// @description 该后端主要用于对接支付接口
+// @host localhost:12345
+// @BasePath /yuexin-pay
+// @version v20240226
+func main() {
+	c_log.GlobalLogger.Info("配置文件为:", ApplicationYaml)
+	// 创建 gin 实例
+	router := gin.Default()
+	// 使用中间件
+	router.Use(middleware.LogRequest())                                                              // 请求日志打印
+	router.Use(middleware.ValidateHeaders(ApplicationYaml.Web.WhiteList, ApplicationYaml.Web.Token)) // 全局请求头校验
+	// 通过路由组设置全局前缀
+	projectPrefix := router.Group(ApplicationYaml.Web.RoutePrefix)
+	// hello 测试接口
+	apiTest := projectPrefix.Group("/test")
+	apiTest.GET("/hello", handler.Hello)
+	// YunGouOs 支付接口
+	apiYunGouOs := projectPrefix.Group("/yungouos")
+	apiYunGouOs.GET("/hello", handler.Hello)
+	// 端口
+	err := router.Run(":" + ApplicationYaml.Web.Port)
+	if err != nil {
+		c_log.GlobalLogger.Error("程序崩溃,监听端口 "+ApplicationYaml.Web.Port+" 失败:", err)
+		os.Exit(-1)
+	}
+}

+ 30 - 0
common/config/c_db/c_sqlx_config.go

@@ -0,0 +1,30 @@
+package c_db
+
+import (
+	"cicv-data-closedloop/common/config/c_log"
+	_ "github.com/go-sql-driver/mysql"
+	"github.com/jmoiron/sqlx"
+	"os"
+)
+
+var MysqlDb *sqlx.DB
+
+// InitSqlxMysql 初始化mysql连接
+// - charset 字符集 utf8、utf8mb4
+func InitSqlxMysql(username string, password string, ip string, port string, dbname string, charset string) {
+	var err error
+	// 连接数据库
+	// - parseTime 是否将数据库中的时间类型字段解析为 Go 中的 time.Time 类型。
+	// - loc 时间解析时使用的本地位置信息。通常设置为 "Local"。
+	MysqlDb, err = sqlx.Open("mysql", username+":"+password+"@tcp("+ip+":"+port+")/"+dbname+"?charset="+charset+"&parseTime=True&loc=Local")
+	if err != nil {
+		c_log.GlobalLogger.Error("程序退出。mysql连接失败:", err)
+		os.Exit(-1)
+	}
+
+	// 配置连接池
+	MysqlDb.SetMaxOpenConns(10)   // 设置最大打开连接数为 10
+	MysqlDb.SetMaxIdleConns(5)    // 设置最大空闲连接数为 5
+	MysqlDb.SetConnMaxLifetime(0) // 设置连接的最大生存时间为 0(不限制)
+	c_log.GlobalLogger.Info("mysql连接成功。")
+}

+ 3 - 0
common/entity/http_result.go

@@ -1,5 +1,8 @@
 package entity
 
+var DefaultSuccessHttpResult = &HttpResult{Status: true, Code: "1000", Message: "请求成功。"}
+var DefaultFailHttpResult = &HttpResult{Status: true, Code: "2000", Message: "请求失败。"}
+
 type HttpResult struct {
 	Status  bool   `json:"status"`
 	Code    string `json:"code"`

+ 39 - 0
common/gin/handler/h_hello.go

@@ -0,0 +1,39 @@
+package handler
+
+import (
+	"cicv-data-closedloop/common/config/c_db"
+	"cicv-data-closedloop/common/config/c_log"
+	"cicv-data-closedloop/common/entity"
+	"github.com/gin-gonic/gin"
+	"net/http"
+)
+
+type testStruct struct {
+	Id   int    `db:"id"`
+	Name string `db:"name"`
+}
+
+// Hello 测试接口
+// @Tags 此标记的所有接口均用于测试
+// @Summary 测试
+// @Description 该接口用于测试使用
+// @Param param query int true "Id"     参数 :@Param 参数名 位置(query 或者 path或者 body) 类型 是否必需 注释
+// @Produce json
+// @Success 200 {object} entity.HttpResult
+// @Router /test/hello [get]
+func Hello(c *gin.Context) {
+	// 获取请求参数
+	param := c.Query("param")
+	c_log.GlobalLogger.Info("接受到请求参数:", param)
+	var tests []testStruct
+	// 查询数据库
+	var testSql string
+	if err := c_db.MysqlDb.Select(&tests, testSql); err != nil {
+		c_log.GlobalLogger.Error("数据库查询报错:", err)
+		c.JSON(http.StatusInternalServerError, entity.DefaultFailHttpResult)
+		return
+	}
+	c_log.GlobalLogger.Info("数据库查询成功:", tests)
+
+	c.JSON(http.StatusOK, entity.DefaultSuccessHttpResult)
+}

+ 24 - 0
common/gin/middleware/m_log_request.go

@@ -0,0 +1,24 @@
+package middleware
+
+import (
+	"cicv-data-closedloop/common/config/c_log"
+	"github.com/gin-gonic/gin"
+)
+
+/*
+`::1` 是 IPv6 地址中的本地主机地址,相当于 IPv4 中的 `127.0.0.1`,即本地回环地址。在 IPv6 地址中,`::1` 表示本地主机,通常用于代表本地计算机与本地服务进行通信,例如访问本地运行的服务器或服务。
+在Gin框架中,`c.ClientIP()` 方法会尝试解析客户端的真实IP地址。然而,对于本地回环地址 `::1` 或者 `127.0.0.1`,这个方法可能会返回本地回环地址而不是实际的公共 IP 地址。在实际的网络部署中,您可能会看到类似 `::1` 或 `127.0.0.1` 的地址,特别是在开发和测试环境中。
+如果您希望获取请求的真实IP地址,而不是本地回环地址,可以考虑使用一些反向代理服务器或负载均衡器,它们通常会在请求头中添加一个字段来传递客户端的真实IP地址。在Gin中,您可以使用`c.Request.Header.Get("X-Real-IP")`或`c.Request.Header.Get("X-Forwarded-For")`来获取这些头部信息中的真实IP地址。请注意,使用这些方法时需要谨慎,确保信任传递的 IP 地址信息,以防止IP欺骗等安全问题。
+*/
+
+// LogRequest 中间件函数,用于打印请求方的IP地址和请求路径
+func LogRequest() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		clientIP := c.ClientIP()          // 获取请求方的IP地址
+		requestPath := c.Request.URL.Path // 获取请求路径
+		// 打印请求方的IP地址和请求路径
+		c_log.GlobalLogger.Infof("客户端 %v 发送请求 %v", clientIP, requestPath)
+		// 继续处理后续请求
+		c.Next()
+	}
+}

+ 34 - 0
common/gin/middleware/m_validate_header.go

@@ -0,0 +1,34 @@
+package middleware
+
+import (
+	"cicv-data-closedloop/common/config/c_log"
+	"cicv-data-closedloop/common/entity"
+	"github.com/gin-gonic/gin"
+	"net/http"
+	"strings"
+)
+
+func ValidateHeaders(whiteList []string, webToken string) gin.HandlerFunc {
+	return func(c *gin.Context) {
+		// 校验不在白名单中的路由
+		if isNotWhite(c.Request.URL.Path, whiteList) {
+			acceptToken := c.GetHeader("Authorization")
+			if acceptToken == "" || acceptToken != webToken {
+				c_log.GlobalLogger.Errorf("请求头 Authorization 校验失败:%v --> %v", acceptToken, webToken)
+				c.JSON(http.StatusOK, entity.HttpResult{Status: false, Code: "1001", Message: "请求头 Authorization 校验失败。"})
+				c.Abort()
+				return
+			}
+		}
+		c.Next()
+	}
+}
+
+func isNotWhite(path string, whiteList []string) bool {
+	for _, whitePath := range whiteList {
+		if strings.HasPrefix(path, whitePath) {
+			return false
+		}
+	}
+	return true
+}

+ 52 - 0
common/gin/middleware/m_whitelist.go

@@ -0,0 +1,52 @@
+package middleware
+
+import (
+	"github.com/gin-gonic/gin"
+	"net/http"
+)
+
+var (
+	whitelistIP = map[string]bool{
+		"192.168.1.100": true,
+		"10.0.0.1":      true,
+		// 添加更多的白名单IP地址
+	}
+	whitelistRoutes = map[string]bool{
+		"/yuexin-pay/swagger": true,
+		// 添加更多的白名单路由
+	}
+)
+
+// WhitelistMiddleware 白名单中间件
+func WhitelistMiddleware() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		// 检查IP地址
+		clientIP := c.ClientIP()
+		if !isIPInWhitelist(clientIP) {
+			c.JSON(http.StatusForbidden, gin.H{"error": "IP地址不在白名单中"})
+			c.Abort()
+			return
+		}
+
+		// 检查路由
+		if !isRouteInWhitelist(c.FullPath()) {
+			c.JSON(http.StatusForbidden, gin.H{"error": "路由不在白名单中"})
+			c.Abort()
+			return
+		}
+
+		c.Next()
+	}
+}
+
+// isIPInWhitelist 检查IP地址是否在白名单中
+func isIPInWhitelist(ip string) bool {
+	_, ok := whitelistIP[ip]
+	return ok
+}
+
+// isRouteInWhitelist 检查路由是否在白名单中
+func isRouteInWhitelist(route string) bool {
+	_, ok := whitelistRoutes[route]
+	return ok
+}

+ 2 - 0
go.mod

@@ -32,12 +32,14 @@ require (
 	github.com/go-playground/locales v0.14.1 // indirect
 	github.com/go-playground/universal-translator v0.18.1 // indirect
 	github.com/go-playground/validator/v10 v10.17.0 // indirect
+	github.com/go-sql-driver/mysql v1.7.1 // indirect
 	github.com/goccy/go-json v0.10.2 // indirect
 	github.com/golang/mock v1.6.0 // indirect
 	github.com/golang/protobuf v1.5.3 // indirect
 	github.com/google/go-cmp v0.6.0 // indirect
 	github.com/gookit/color v1.5.4 // indirect
 	github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
+	github.com/jmoiron/sqlx v1.3.5 // indirect
 	github.com/json-iterator/go v1.1.12 // indirect
 	github.com/klauspost/cpuid/v2 v2.2.6 // indirect
 	github.com/kr/text v0.2.0 // indirect

+ 7 - 0
go.sum

@@ -117,6 +117,9 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
 github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
 github.com/go-playground/validator/v10 v10.17.0 h1:SmVVlfAOtlZncTxRuinDPomC2DkXJ4E5T9gDA0AIH74=
 github.com/go-playground/validator/v10 v10.17.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
+github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
+github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
+github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
 github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
 github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
 github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
@@ -188,6 +191,8 @@ github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
 github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
 github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
 github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
+github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
+github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
 github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
 github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
 github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
@@ -216,8 +221,10 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
 github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
 github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
 github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
+github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
 github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
 github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
 github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=