67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
package routers
|
|
|
|
import (
|
|
"log"
|
|
"main/configs"
|
|
"main/models"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
)
|
|
|
|
func WebpGet(w http.ResponseWriter, r *http.Request) {
|
|
// 獲取請求參數(id, version, width, height, fit, format)
|
|
reg := regexp.MustCompile(`^/img/([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) != 7 {
|
|
log.Println("URL 格式错误", matches)
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
version, fit, format := matches[2], matches[5], matches[6]
|
|
|
|
// id 轉換爲數字
|
|
id, err := strconv.ParseInt(matches[1], 10, 64)
|
|
if err != nil {
|
|
log.Println("ID 格式错误", matches[1])
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
// width 轉換爲數字
|
|
width, err := strconv.Atoi(matches[3])
|
|
if err != nil {
|
|
log.Println("width 格式错误", matches[3])
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
// height 轉換爲數字
|
|
height, err := strconv.Atoi(matches[4])
|
|
if err != nil {
|
|
log.Println("height 格式错误", matches[4])
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
// 從數據庫中獲取圖片信息
|
|
var image models.Image = models.Image{ID: int(id)}
|
|
if err := configs.ORMDB().Where("id = ?", id).First(&image).Error; err != nil {
|
|
log.Println("获取图片失败", version, format, err)
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
data, err := image.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)
|
|
}
|