This commit is contained in:
2023-04-08 14:07:35 +08:00
parent 4ac65db98a
commit 0463d3be41
2 changed files with 77 additions and 4 deletions

View File

@@ -39,6 +39,38 @@ func main() {
var mysqlConnection models.MysqlConnection
mysqlConnection.Init()
http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
// URL 格式: /img/{type}/{id}.{format}?width=320&height=320&fit=cover
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) != 5 {
log.Println("URL 格式错误", matches)
w.WriteHeader(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.StatusBadRequest)
}
var img models.Image
img.Init(content)
data, err := img.ToWebP(width, height, fit)
if err != nil {
log.Println("转换图片失败", err)
w.WriteHeader(http.StatusBadRequest)
}
w.Header().Set("Content-Type", "image/webp")
w.Header().Set("Cache-Control", "max-age=31536000")
w.Write(data)
})
// 直接走 CDN 的请求不缓存本地, 因此直接使用参数
http.HandleFunc("/webp/", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
@@ -72,6 +104,37 @@ func main() {
w.Write(data)
})
http.HandleFunc("/article/", func(w http.ResponseWriter, r *http.Request) {
// URL 格式: /article/{id}.{格式}?width=320&height=320&fit=cover
reg := regexp.MustCompile(`^/article/([0-9a-zA-Z]+).(jpg|jpeg|png|webp)$`)
matches := reg.FindStringSubmatch(r.URL.Path)
if len(matches) != 3 {
log.Println("URL 格式错误", matches)
w.WriteHeader(http.StatusNotFound)
return
}
id, format, width, height, fit := matches[1], matches[2], stringToInt(r.URL.Query().Get("width"), 0), stringToInt(r.URL.Query().Get("height"), 0), r.URL.Query().Get("fit")
content, err := mysqlConnection.GetArticleImageContent(id)
if err != nil {
log.Println("获取图片失败", format, err)
w.WriteHeader(http.StatusBadRequest)
}
var img models.Image
img.Init(content)
data, err := img.ToWebP(width, height, fit)
if err != nil {
log.Println("转换图片失败", err)
w.WriteHeader(http.StatusBadRequest)
}
w.Header().Set("Content-Type", "image/webp")
w.Header().Set("Cache-Control", "max-age=31536000")
w.Write(data)
})
http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
// URL 格式: /img/{id}-{version}@{倍图}{宽度}.{格式}
reg := regexp.MustCompile(`^/img/([0-9a-zA-Z]+)-([0-9a-zA-Z]+)@([0-9]{1,4})x([0-9]{1,4}).(jpg|jpeg|png|webp)$`)