refactor(main, logging, utils): Refactor logging and IP extraction logic

Move setupLogging to logging package and create GetRealIP utility function
This commit is contained in:
wood chen 2024-10-26 15:46:00 +08:00
parent 39155ac1bb
commit 96f41e374f
4 changed files with 51 additions and 37 deletions

17
logging/logging.go Normal file
View File

@ -0,0 +1,17 @@
package logging
import (
"io"
"log"
"os"
)
func SetupLogging() {
logFile, err := os.OpenFile("data/server.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
multiWriter := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(multiWriter)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

41
main.go
View File

@ -3,16 +3,16 @@ package main
import (
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"random-api-go/logging"
"random-api-go/stats"
"random-api-go/utils"
"strings"
"sync"
"syscall"
@ -95,8 +95,8 @@ func main() {
source := rand.NewSource(time.Now().UnixNano())
rng = rand.New(source)
setupLogging()
statsManager = stats.NewStatsManager("stats.json")
logging.SetupLogging()
statsManager = stats.NewStatsManager("data/stats.json")
// 设置优雅关闭
c := make(chan os.Signal, 1)
@ -132,37 +132,6 @@ func main() {
}
}
func setupLogging() {
logFile, err := os.OpenFile("server.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
multiWriter := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(multiWriter)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func getRealIP(r *http.Request) string {
ip := r.Header.Get("X-Real-IP")
if ip != "" {
return ip
}
ip = r.Header.Get("X-Forwarded-For")
if ip != "" {
ips := strings.Split(ip, ",")
if len(ips) > 0 {
return strings.TrimSpace(ips[0])
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}
func loadCSVPaths() error {
jsonPath := filepath.Join("public", "url.json")
log.Printf("Attempting to read file: %s", jsonPath)
@ -224,7 +193,7 @@ func getCSVContent(path string) (*URLSelector, error) {
func handleAPIRequest(w http.ResponseWriter, r *http.Request) {
start := time.Now()
realIP := getRealIP(r)
realIP := utils.GetRealIP(r)
referer := r.Referer()
// 获取来源域名

View File

@ -99,7 +99,7 @@ location ^~ / {
## 日志
日志文件位于 `logs/server.log`。使用 Docker Compose 时,可以通过卷挂载访问日志。
日志文件位于 `/root/data/server.log`。使用 Docker Compose 时,可以通过卷挂载访问日志。
## 贡献

28
utils/utils.go Normal file
View File

@ -0,0 +1,28 @@
package utils
import (
"net"
"net/http"
"strings"
)
func GetRealIP(r *http.Request) string {
ip := r.Header.Get("X-Real-IP")
if ip != "" {
return ip
}
ip = r.Header.Get("X-Forwarded-For")
if ip != "" {
ips := strings.Split(ip, ",")
if len(ips) > 0 {
return strings.TrimSpace(ips[0])
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}