From 3a90035be3bf9bc0838d9d7dbd5ee242cbe4e536 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A1=9C=E8=8F=AF?= Date: Sun, 9 Apr 2023 05:59:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A5=E5=BF=97=E7=9A=84=E4=BC=98=E9=9B=85?= =?UTF-8?q?=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/main.go | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/bin/main.go b/bin/main.go index 649f75f..69132bf 100644 --- a/bin/main.go +++ b/bin/main.go @@ -1,9 +1,11 @@ package main import ( + "fmt" "log" "net/http" "runtime" + "time" "regexp" "strconv" @@ -12,9 +14,9 @@ import ( _ "github.com/go-sql-driver/mysql" ) -func init() { - log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) -} +//func init() { +// log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) +//} // string 转换为 int, 如果转换失败则返回默认值 func stringToInt(str string, defaultValue int) int { @@ -28,6 +30,11 @@ func stringToInt(str string, defaultValue int) int { return value } +func LogComponent(startTime int64, r *http.Request) { + endTime := fmt.Sprintf("%dms", (time.Now().UnixNano()-startTime)/1000000) + log.Println(r.Method, r.URL.Path, endTime) +} + func main() { runtime.GOMAXPROCS(runtime.NumCPU()) @@ -36,19 +43,19 @@ func main() { // URL 格式: /img/{type}-{id}.{format}?width=320&height=320&fit=cover http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) { - log.Println(r.Method, r.URL.Path) + defer LogComponent(time.Now().UnixNano(), r) // 最后打印日志 + reg := regexp.MustCompile(`^/img/([0-9a-zA-Z]+)-([0-9a-zA-Z]+).(jpg|jpeg|png|webp)$`) matches := reg.FindStringSubmatch(r.URL.Path) if len(matches) != 4 { - log.Println("URL 格式错误", matches) - w.WriteHeader(http.StatusNotFound) + http.Error(w, "URL 格式错误", http.StatusNotFound) return } group, id, format, width, height, fit := matches[1], matches[2], matches[3], stringToInt(r.URL.Query().Get("width"), 0), stringToInt(r.URL.Query().Get("height"), 0), r.URL.Query().Get("fit") content, err := mysqlConnection.GetImageContent(group, id) if err != nil { log.Println("获取图片失败", format, err) - w.WriteHeader(http.StatusNotFound) + http.Error(w, err.Error(), http.StatusNotFound) return } var img models.Image @@ -56,7 +63,7 @@ func main() { data, err := img.ToWebP(width, height, fit) if err != nil { log.Println("转换图片失败", err) - w.WriteHeader(http.StatusBadRequest) + http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -67,7 +74,8 @@ func main() { // URL 格式: /webp/{type}-{id}-{version}-{width}-{height}-{fit}.{format} http.HandleFunc("/webp/", func(w http.ResponseWriter, r *http.Request) { - log.Println(r.Method, r.URL.Path) + defer LogComponent(time.Now().UnixNano(), r) // 最后打印日志 + reg := regexp.MustCompile(`^/webp/([0-9a-zA-Z]+)-([0-9a-zA-Z]+)-([0-9a-zA-Z]+)-([0-9]+)-([0-9]+)-([a-zA-Z]+).(jpg|jpeg|png|webp)$`) matches := reg.FindStringSubmatch(r.URL.Path) if len(matches) != 8 {