diff --git a/bin/main.go b/bin/main.go index af2e8b6..19b7668 100644 --- a/bin/main.go +++ b/bin/main.go @@ -65,6 +65,37 @@ func main() { w.Write(data) }) + // 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) + 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) != 4 { + log.Println("URL 格式错误", matches) + w.WriteHeader(http.StatusNotFound) + return + } + group, id, version, width, height, fit, format := matches[1], matches[2], matches[3], stringToInt(matches[4], 0), stringToInt(matches[5], 0), matches[6], matches[7] + content, err := mysqlConnection.GetImageContent(group, id) + if err != nil { + log.Println("获取图片失败", version, format, err) + w.WriteHeader(http.StatusNotFound) + return + } + var img models.Image + img.Init(content) + data, err := img.ToWebP(width, height, fit) + if err != nil { + log.Println("转换图片失败", err) + w.WriteHeader(http.StatusBadRequest) + return + } + + w.Header().Set("Content-Type", "image/webp") + w.Header().Set("Cache-Control", "max-age=31536000") + w.Write(data) + }) + log.Println("Server is running at http://localhost:6001") http.ListenAndServe(":6001", nil) } diff --git a/main b/main new file mode 100755 index 0000000..c34bbcc Binary files /dev/null and b/main differ