数据结构优化

This commit is contained in:
李琦
2026-01-20 10:36:27 +08:00
parent c1324aa87c
commit 29a642c285
8 changed files with 130 additions and 18 deletions

3
.gitignore vendored
View File

@@ -1,4 +1,5 @@
client/node_modules client/node_modules
.trae .trae
.idea .idea
docs docs
client/dist

View File

@@ -1,4 +1,5 @@
export const API_BASE = 'http://localhost:8081/api' // export const API_BASE = 'http://localhost:8081/api'
export const API_BASE = '/api'
// 通用请求头配置 // 通用请求头配置
export const getAuthHeaders = () => { export const getAuthHeaders = () => {

View File

@@ -4,7 +4,9 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"path/filepath"
"github.com/joho/godotenv"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
@@ -15,6 +17,39 @@ var DB *gorm.DB
// JWTSecret is the secret key used for signing JWT tokens // JWTSecret is the secret key used for signing JWT tokens
var JWTSecret = "your-secret-key" // Default value, should be set via JWT_SECRET environment variable in production var JWTSecret = "your-secret-key" // Default value, should be set via JWT_SECRET environment variable in production
// LoadEnvFile 从可执行文件同级目录加载 .env 文件
func LoadEnvFile() {
// 获取可执行文件路径
execPath, err := os.Executable()
if err != nil {
log.Printf("Warning: Failed to get executable path: %v. Using current working directory.", err)
// 如果获取可执行文件路径失败,使用当前工作目录
if err := godotenv.Load(".env"); err != nil {
log.Printf("Info: .env file not found in current directory: %v", err)
} else {
log.Println("Loaded .env file from current directory")
}
return
}
// 获取可执行文件所在目录
execDir := filepath.Dir(execPath)
envPath := filepath.Join(execDir, ".env")
// 检查 .env 文件是否存在
if _, err := os.Stat(envPath); os.IsNotExist(err) {
log.Printf("Info: .env file not found at %s, using environment variables or defaults", envPath)
return
}
// 加载 .env 文件
if err := godotenv.Load(envPath); err != nil {
log.Printf("Warning: Failed to load .env file from %s: %v", envPath, err)
} else {
log.Printf("Loaded .env file from %s", envPath)
}
}
func InitDB() { func InitDB() {
var err error var err error
@@ -22,6 +57,7 @@ func InitDB() {
dsn := os.Getenv("DB_DSN") dsn := os.Getenv("DB_DSN")
if dsn == "" { if dsn == "" {
dsn = "root:root@tcp(127.0.0.1:3306)/nl_blog?charset=utf8mb4&parseTime=True&loc=Local" dsn = "root:root@tcp(127.0.0.1:3306)/nl_blog?charset=utf8mb4&parseTime=True&loc=Local"
//dsn = "root:mysql_PKC65h@tcp(127.0.0.1:3306)/nl_blog?charset=utf8mb4&parseTime=True&loc=Local"
} }
// Try to get JWT secret from environment variable // Try to get JWT secret from environment variable

View File

@@ -3,12 +3,14 @@ module github.com/niangaodev/art-code
go 1.25.5 go 1.25.5
require ( require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
github.com/gin-gonic/gin v1.11.0 github.com/gin-gonic/gin v1.11.0
github.com/go-sql-driver/mysql v1.9.3 github.com/go-sql-driver/mysql v1.9.3
github.com/golang-jwt/jwt/v5 v5.3.0 github.com/golang-jwt/jwt/v5 v5.3.0
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20260109033043-398149f17e54 github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20260109033043-398149f17e54
github.com/qiniu/go-sdk/v7 v7.25.6
github.com/tencentyun/cos-go-sdk-v5 v0.7.72
golang.org/x/crypto v0.40.0 golang.org/x/crypto v0.40.0
gorm.io/driver/mysql v1.5.7 gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.12 gorm.io/gorm v1.25.12
@@ -18,7 +20,6 @@ require (
filippo.io/edwards25519 v1.1.0 // indirect filippo.io/edwards25519 v1.1.0 // indirect
github.com/BurntSushi/toml v1.3.2 // indirect github.com/BurntSushi/toml v1.3.2 // indirect
github.com/alex-ant/gomath v0.0.0-20160516115720-89013a210a82 // indirect github.com/alex-ant/gomath v0.0.0-20160516115720-89013a210a82 // indirect
github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible // indirect
github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/clbanning/mxj v1.8.4 // indirect github.com/clbanning/mxj v1.8.4 // indirect
@@ -35,6 +36,7 @@ require (
github.com/google/go-querystring v1.0.0 // indirect github.com/google/go-querystring v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
@@ -44,10 +46,8 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mozillazg/go-httpheader v0.2.1 // indirect github.com/mozillazg/go-httpheader v0.2.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/qiniu/go-sdk/v7 v7.25.6 // indirect
github.com/quic-go/qpack v0.5.1 // indirect github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect github.com/quic-go/quic-go v0.54.0 // indirect
github.com/tencentyun/cos-go-sdk-v5 v0.7.72 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect github.com/ugorji/go/codec v1.3.0 // indirect
go.uber.org/mock v0.5.0 // indirect go.uber.org/mock v0.5.0 // indirect

View File

@@ -19,8 +19,6 @@ github.com/dave/jennifer v1.6.1/go.mod h1:nXbxhEmQfOZhWml3D1cDK5M1FLnMSozpbFN/m3
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gammazero/toposort v0.1.1 h1:OivGxsWxF3U3+U80VoLJ+f50HcPU1MIqE1JlKzoJ2Eg= github.com/gammazero/toposort v0.1.1 h1:OivGxsWxF3U3+U80VoLJ+f50HcPU1MIqE1JlKzoJ2Eg=
@@ -63,6 +61,7 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
@@ -70,15 +69,19 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
@@ -110,6 +113,7 @@ github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg= github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY= github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529/go.mod h1:qe5TWALJ8/a1Lqznoc5BDHpYX/8HU60Hm2AwRmqzxqA= github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529/go.mod h1:qe5TWALJ8/a1Lqznoc5BDHpYX/8HU60Hm2AwRmqzxqA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -169,6 +173,7 @@ google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7I
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@@ -2,6 +2,7 @@ package main
import ( import (
"log" "log"
"os"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/niangaodev/art-code/config" "github.com/niangaodev/art-code/config"
@@ -11,6 +12,9 @@ import (
) )
func main() { func main() {
// 加载 .env 文件(必须在其他初始化之前)
config.LoadEnvFile()
// 初始化数据库连接 // 初始化数据库连接
config.InitDB() config.InitDB()
defer config.CloseDB() defer config.CloseDB()
@@ -19,8 +23,8 @@ func main() {
// repositories.MigrateToBigInt() // 已禁用自动迁移 // repositories.MigrateToBigInt() // 已禁用自动迁移
// 初始化ip2region (如果文件不存在将降级为普通IP记录) // 初始化ip2region (如果文件不存在将降级为普通IP记录)
// 请确保在server根目录或合适位置放入 ip2region.xdb // 函数会自动从环境变量或可执行文件目录查找 ip2region.xdb
utils.InitIP2Region("ip2region.xdb") utils.InitIP2Region("")
// 创建Gin引擎 // 创建Gin引擎
router := gin.New() router := gin.New()
@@ -31,7 +35,16 @@ func main() {
router.Use(gin.Recovery()) router.Use(gin.Recovery())
// 静态文件服务 - 用于访问上传的本地文件 // 静态文件服务 - 用于访问上传的本地文件
router.Static("/uploads", "./uploads") // 从环境变量读取配置,如果未设置则使用默认值
uploadsBaseURL := os.Getenv("UPLOADS_BASE_URL")
if uploadsBaseURL == "" {
uploadsBaseURL = "/uploads"
}
uploadsBasePath := os.Getenv("UPLOADS_BASE_PATH")
if uploadsBasePath == "" {
uploadsBasePath = "./uploads"
}
router.Static(uploadsBaseURL, uploadsBasePath)
// API路由组 // API路由组
api := router.Group("/api") api := router.Group("/api")
@@ -215,7 +228,7 @@ func main() {
} }
// 启动服务器 // 启动服务器
log.Println("Server running on http://localhost:8081") log.Println("Server running on http://localhost:18081")
if err := router.Run(":8081"); err != nil { if err := router.Run(":8081"); err != nil {
log.Fatalf("Failed to start server: %v", err) log.Fatalf("Failed to start server: %v", err)
} }

View File

@@ -3,6 +3,8 @@ package utils
import ( import (
"log" "log"
"net" "net"
"os"
"path/filepath"
"sync" "sync"
"github.com/lionsoul2014/ip2region/binding/golang/xdb" "github.com/lionsoul2014/ip2region/binding/golang/xdb"
@@ -15,28 +17,73 @@ var (
// InitIP2Region 初始化 ip2region // InitIP2Region 初始化 ip2region
// 需要 ip2region.xdb 文件如果不存在则仅支持基本IP解析 // 需要 ip2region.xdb 文件如果不存在则仅支持基本IP解析
// 如果 dbPath 为空,将自动从环境变量或可执行文件目录查找
func InitIP2Region(dbPath string) { func InitIP2Region(dbPath string) {
once.Do(func() { once.Do(func() {
var err error var err error
// 1. 尝试加载整个xdb到内存性能最好 var finalPath string
cBuff, err := xdb.LoadContentFromFile(dbPath)
// 1. 如果传入了路径,直接使用
if dbPath != "" {
finalPath = dbPath
} else {
// 2. 优先从环境变量读取
finalPath = os.Getenv("IP2REGION_DB_PATH")
if finalPath == "" {
// 3. 尝试在可执行文件同级目录查找
execPath, err := os.Executable()
if err == nil {
execDir := filepath.Dir(execPath)
candidatePath := filepath.Join(execDir, "ip2region.xdb")
if _, err := os.Stat(candidatePath); err == nil {
finalPath = candidatePath
}
}
// 4. 如果还没找到,尝试当前工作目录(兼容开发环境)
if finalPath == "" {
candidatePath := "./ip2region.xdb"
if _, err := os.Stat(candidatePath); err == nil {
finalPath = candidatePath
}
}
}
}
// 如果最终路径为空,说明找不到文件
if finalPath == "" {
log.Printf("IP2Region database file not found. Region lookup will be disabled.")
searcher = nil
return
}
// 5. 尝试加载整个xdb到内存性能最好
cBuff, err := xdb.LoadContentFromFile(finalPath)
if err != nil { if err != nil {
log.Printf("Failed to load ip2region.xdb: %v. Region lookup will be disabled.", err) log.Printf("Failed to load ip2region.xdb from %s: %v. Region lookup will be disabled.", finalPath, err)
searcher = nil
return return
} }
searcher, err = xdb.NewWithBuffer(nil, cBuff) searcher, err = xdb.NewWithBuffer(nil, cBuff)
if err != nil { if err != nil {
log.Printf("Failed to create searcher: %v", err) log.Printf("Failed to create searcher: %v", err)
searcher = nil
return return
} }
log.Println("IP2Region loaded successfully") log.Printf("IP2Region loaded successfully from %s", finalPath)
}) })
} }
// GetRegion 获取IP归属地 // GetRegion 获取IP归属地
// 返回格式: 国家|区域|省份|城市|ISP // 返回格式: 国家|区域|省份|城市|ISP
func GetRegion(ip string) string { func GetRegion(ip string) string {
// 添加 recover 保护,防止 panic 导致整个请求失败
defer func() {
if r := recover(); r != nil {
log.Printf("Panic in GetRegion for IP %s: %v", ip, r)
}
}()
if searcher == nil { if searcher == nil {
return "Unknown" return "Unknown"
} }

View File

@@ -68,9 +68,18 @@ type OSSUploader interface {
func GetOSSUploader(config *OSSConfig) (OSSUploader, error) { func GetOSSUploader(config *OSSConfig) (OSSUploader, error) {
switch StorageType(config.StorageType) { switch StorageType(config.StorageType) {
case StorageLocal: case StorageLocal:
// 从环境变量读取配置,如果未设置则使用默认值
basePath := os.Getenv("UPLOADS_BASE_PATH")
if basePath == "" {
basePath = "./uploads"
}
baseURL := os.Getenv("UPLOADS_BASE_URL")
if baseURL == "" {
baseURL = "/uploads"
}
return &LocalUploader{ return &LocalUploader{
BasePath: "./uploads", BasePath: basePath,
BaseURL: "/uploads", BaseURL: baseURL,
}, nil }, nil
case StorageQCloud: case StorageQCloud:
// 优先使用专用字段,如果为空则使用通用字段(向后兼容) // 优先使用专用字段,如果为空则使用通用字段(向后兼容)