Extract checkAllowedType function.

Minor Log text optimization.
This commit is contained in:
n0vad3v 2021-12-05 22:20:39 +08:00
parent 67d40b4397
commit 5e033a8f72
No known key found for this signature in database
GPG Key ID: 8D42A0E699E50639
3 changed files with 28 additions and 26 deletions

View File

@ -112,7 +112,7 @@ func avifEncoder(p1, p2 string, quality float32) {
var avifQuality = int((100 - quality) / 100 * avif.MaxQuality) var avifQuality = int((100 - quality) / 100 * avif.MaxQuality)
err = avif.Encode(dst, img, &avif.Options{Quality: avifQuality}) err = avif.Encode(dst, img, &avif.Options{Quality: avifQuality})
if err != nil { if err != nil {
log.Fatalf("Can't encode source image: %v", err) log.Fatalf("Can't encode source image: %v to AVIF", err)
} }
convertLog("AVIF", p1, p2, quality) convertLog("AVIF", p1, p2, quality)
@ -128,9 +128,9 @@ func webpEncoder(p1, p2 string, quality float32) {
return return
} }
if err := webp.Encode(&buf, img, &webp.Options{Lossless: false, Quality: quality}); err != nil { err = webp.Encode(&buf, img, &webp.Options{Lossless: false, Quality: quality})
log.Error(err) if err != nil {
return log.Fatalf("Can't encode source image: %v to WebP", err)
} }
if err := ioutil.WriteFile(p2, buf.Bytes(), 0644); err != nil { if err := ioutil.WriteFile(p2, buf.Bytes(), 0644); err != nil {

View File

@ -3,7 +3,6 @@ package main
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/valyala/fasthttp"
"hash/crc32" "hash/crc32"
"io" "io"
"io/ioutil" "io/ioutil"
@ -13,9 +12,12 @@ import (
"path/filepath" "path/filepath"
"strconv" "strconv"
"github.com/valyala/fasthttp"
"strings"
"github.com/h2non/filetype" "github.com/h2non/filetype"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"strings"
) )
func avifMatcher(buf []byte) bool { func avifMatcher(buf []byte) bool {
@ -61,6 +63,17 @@ func imageExists(filename string) bool {
return !info.IsDir() return !info.IsDir()
} }
func checkAllowedType(imgFilename string) bool {
imgFilename = strings.ToLower(imgFilename)
for _, allowedType := range config.AllowedTypes {
allowedType = "." + strings.ToLower(allowedType)
if strings.HasSuffix(imgFilename, allowedType) {
return true
}
}
return false
}
// Check for remote filepath, e.g: https://test.webp.sh/node.png // Check for remote filepath, e.g: https://test.webp.sh/node.png
// return StatusCode, etagValue and length // return StatusCode, etagValue and length
func getRemoteImageInfo(fileUrl string) (int, string, string) { func getRemoteImageInfo(fileUrl string) (int, string, string) {
@ -124,6 +137,7 @@ func genOptimizedAbs(rawImagePath string, exhaustPath string, imageName string,
ModifiedTime := STAT.ModTime().Unix() ModifiedTime := STAT.ModTime().Unix()
// webpFilename: abc.jpg.png -> abc.jpg.png.1582558990.webp // webpFilename: abc.jpg.png -> abc.jpg.png.1582558990.webp
webpFilename := fmt.Sprintf("%s.%d.webp", imageName, ModifiedTime) webpFilename := fmt.Sprintf("%s.%d.webp", imageName, ModifiedTime)
// avifFilename: abc.jpg.png -> abc.jpg.png.1582558990.avif
avifFilename := fmt.Sprintf("%s.%d.avif", imageName, ModifiedTime) avifFilename := fmt.Sprintf("%s.%d.avif", imageName, ModifiedTime)
// /home/webp_server/exhaust/path/to/tsuki.jpg.1582558990.webp // /home/webp_server/exhaust/path/to/tsuki.jpg.1582558990.webp
@ -148,16 +162,16 @@ func genEtag(ImgAbsPath string) string {
func getCompressionRate(RawImagePath string, optimizedImg string) string { func getCompressionRate(RawImagePath string, optimizedImg string) string {
originFileInfo, err := os.Stat(RawImagePath) originFileInfo, err := os.Stat(RawImagePath)
if err != nil { if err != nil {
log.Warnf("fail to get raw image %v", err) log.Warnf("Failed to get raw image %v", err)
return "" return ""
} }
optimizedFileInfo, err := os.Stat(optimizedImg) optimizedFileInfo, err := os.Stat(optimizedImg)
if err != nil { if err != nil {
log.Warnf("fail to get webp image %v", err) log.Warnf("Failed to get optimized image %v", err)
return "" return ""
} }
compressionRate := float64(optimizedFileInfo.Size()) / float64(originFileInfo.Size()) compressionRate := float64(optimizedFileInfo.Size()) / float64(originFileInfo.Size())
log.Debugf("The compress rate is %d/%d=%.2f", originFileInfo.Size(), optimizedFileInfo.Size(), compressionRate) log.Debugf("The compression rate is %d/%d=%.2f", originFileInfo.Size(), optimizedFileInfo.Size(), compressionRate)
return fmt.Sprintf(`%.2f`, compressionRate) return fmt.Sprintf(`%.2f`, compressionRate)
} }

View File

@ -3,14 +3,14 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/gofiber/fiber/v2"
log "github.com/sirupsen/logrus"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"path" "path"
"strings"
"github.com/gofiber/fiber/v2"
log "github.com/sirupsen/logrus"
) )
func convert(c *fiber.Ctx) error { func convert(c *fiber.Ctx) error {
@ -27,7 +27,7 @@ func convert(c *fiber.Ctx) error {
goodFormat := guessSupportedFormat(&c.Request().Header) goodFormat := guessSupportedFormat(&c.Request().Header)
// old browser only // old browser only, send the original image or fetch from remote and send.
if len(goodFormat) == 1 { if len(goodFormat) == 1 {
c.Set("ETag", genEtag(rawImageAbs)) c.Set("ETag", genEtag(rawImageAbs))
if proxyMode { if proxyMode {
@ -39,19 +39,7 @@ func convert(c *fiber.Ctx) error {
} }
} }
var allowed = false if !checkAllowedType(imgFilename) {
for _, ext := range config.AllowedTypes {
haystack := strings.ToLower(imgFilename)
needle := strings.ToLower("." + ext)
if strings.HasSuffix(haystack, needle) {
allowed = true
break
} else {
allowed = false
}
}
if !allowed {
msg := "File extension not allowed! " + imgFilename msg := "File extension not allowed! " + imgFilename
log.Warn(msg) log.Warn(msg)
if imageExists(rawImageAbs) { if imageExists(rawImageAbs) {