Enhance code (#199)

* Enhance code

* Fix wrong comment

* Add cURL test

* Add TestResizeImage

* Close response body
This commit is contained in:
Nova Kwok 2023-05-17 20:50:02 +08:00 committed by GitHub
parent 416c7816ba
commit 651ae512a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 88 additions and 7 deletions

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"github.com/davidbyttow/govips/v2/vips"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"os" "os"
@ -23,6 +24,69 @@ func walker() []string {
return list return list
} }
func TestResizeImage(t *testing.T) {
// Create a test image with specific dimensions
testImage, _ := vips.NewImageFromFile("./pics/png.jpg")
// Test case 1: Both width and height are greater than 0
params1 := ExtraParams{
Width: 100,
Height: 100,
}
err := resizeImage(testImage, params1)
if err != nil {
t.Errorf("Error occurred while resizing image: %v", err)
}
// Assert the resized image has the expected dimensions
resizedWidth1 := testImage.Width()
resizedHeight1 := testImage.Height()
expectedWidth1 := params1.Width
expectedHeight1 := params1.Height
// If both width and height are provided, follow Width and keep aspect ratio
if resizedWidth1 != expectedWidth1 {
t.Errorf("Resized image dimensions do not match. Expected: %dx%d, Actual: %dx%d",
expectedWidth1, expectedHeight1, resizedWidth1, resizedHeight1)
}
// Test case 2: Only width is greater than 0
params2 := ExtraParams{
Width: 100,
Height: 0,
}
err = resizeImage(testImage, params2)
if err != nil {
t.Errorf("Error occurred while resizing image: %v", err)
}
// Assert the resized image has the expected width
resizedWidth2 := testImage.Width()
expectedWidth2 := params2.Width
if resizedWidth2 != expectedWidth2 {
t.Errorf("Resized image width does not match. Expected: %d, Actual: %d",
expectedWidth2, resizedWidth2)
}
// Test case 3: Only height is greater than 0
params3 := ExtraParams{
Width: 0,
Height: 100,
}
err = resizeImage(testImage, params3)
if err != nil {
t.Errorf("Error occurred while resizing image: %v", err)
}
// Assert the resized image has the expected height
resizedHeight3 := testImage.Height()
expectedHeight3 := params3.Height
if resizedHeight3 != expectedHeight3 {
t.Errorf("Resized image height does not match. Expected: %d, Actual: %d",
expectedHeight3, resizedHeight3)
}
}
func TestWebPEncoder(t *testing.T) { func TestWebPEncoder(t *testing.T) {
// Go through every files // Go through every files
var target = walker() var target = walker()

View File

@ -111,6 +111,15 @@ func fetchRemoteImage(filepath string, url string) error {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
// Check if remote content-type is image
if !strings.Contains(resp.Header.Get("content-type"), "image") {
log.Warnf("remote file %s is not image, remote returned %s", url, resp.Header.Get("content-type"))
// Delete the file
_ = os.Remove(filepath)
return fmt.Errorf("remote file %s is not image, remote returned %s", url, resp.Header.Get("content-type"))
}
_ = os.MkdirAll(path.Dir(filepath), 0755) _ = os.MkdirAll(path.Dir(filepath), 0755)
out, err := os.Create(filepath) out, err := os.Create(filepath)
if err != nil { if err != nil {

View File

@ -16,8 +16,11 @@ import (
func convert(c *fiber.Ctx) error { func convert(c *fiber.Ctx) error {
//basic vars //basic vars
var reqURI, _ = url.QueryUnescape(c.Path()) // /mypic/123.jpg var (
var reqURIwithQuery, _ = url.QueryUnescape(c.OriginalURL()) // /mypic/123.jpg?someother=200&somebugs=200 reqURI, _ = url.QueryUnescape(c.Path()) // /mypic/123.jpg
reqURIwithQuery, _ = url.QueryUnescape(c.OriginalURL()) // /mypic/123.jpg?someother=200&somebugs=200
imgFilename = path.Base(reqURI) // pure filename, 123.jpg
)
// Sometimes reqURIwithQuery can be https://example.tld/mypic/123.jpg?someother=200&somebugs=200, we need to extract it. // Sometimes reqURIwithQuery can be https://example.tld/mypic/123.jpg?someother=200&somebugs=200, we need to extract it.
u, err := url.Parse(reqURIwithQuery) u, err := url.Parse(reqURIwithQuery)
if err != nil { if err != nil {
@ -52,7 +55,6 @@ func convert(c *fiber.Ctx) error {
} else { } else {
rawImageAbs = path.Join(config.ImgPath, reqURI) // /home/xxx/mypic/123.jpg rawImageAbs = path.Join(config.ImgPath, reqURI) // /home/xxx/mypic/123.jpg
} }
var imgFilename = path.Base(reqURI) // pure filename, 123.jpg
log.Debugf("Incoming connection from %s %s", c.IP(), imgFilename) log.Debugf("Incoming connection from %s %s", c.IP(), imgFilename)
if !checkAllowedType(imgFilename) { if !checkAllowedType(imgFilename) {
@ -118,9 +120,9 @@ func proxyHandler(c *fiber.Ctx, reqURIwithQuery string) (string, error) {
// Since we cannot store file in format of "mypic/123.jpg?someother=200&somebugs=200", we need to hash it. // Since we cannot store file in format of "mypic/123.jpg?someother=200&somebugs=200", we need to hash it.
reqURIwithQueryHash := Sha1Path(reqURIwithQuery) // 378e740ca56144b7587f3af9debeee544842879a reqURIwithQueryHash := Sha1Path(reqURIwithQuery) // 378e740ca56144b7587f3af9debeee544842879a
localRawImagePath := remoteRaw + "/" + reqURIwithQueryHash // For store the remote raw image, /home/webp_server/remote-raw/378e740ca56144b7587f3af9debeee544842879a localRawImagePath := path.Join(remoteRaw, reqURIwithQueryHash) // For store the remote raw image, /home/webp_server/remote-raw/378e740ca56144b7587f3af9debeee544842879a
// Ping Remote for status code and etag info // Ping Remote for status code and etag info
log.Infof("Remote Addr is %s fetching", realRemoteAddr) log.Infof("Remote Addr is %s, fetching...", realRemoteAddr)
statusCode, _, _ := getRemoteImageInfo(realRemoteAddr) statusCode, _, _ := getRemoteImageInfo(realRemoteAddr)
if statusCode == 200 { if statusCode == 200 {

View File

@ -17,6 +17,7 @@ var (
acceptAvif = "image/avif,image/*,*/*;q=0.8" acceptAvif = "image/avif,image/*,*/*;q=0.8"
acceptLegacy = "image/jpeg" acceptLegacy = "image/jpeg"
safariUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15" safariUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15"
curlUA = "curl/7.64.1"
) )
func setupParam() { func setupParam() {
@ -166,6 +167,11 @@ func TestConvertProxyModeBad(t *testing.T) {
defer resp.Body.Close() defer resp.Body.Close()
assert.Equal(t, http.StatusNotFound, resp.StatusCode) assert.Equal(t, http.StatusNotFound, resp.StatusCode)
// this is local random image, test using cURL, should be 404, ref: https://github.com/webp-sh/webp_server_go/issues/197
resp1, _ := requestToServer(url, app, curlUA, acceptWebP)
defer resp1.Body.Close()
assert.Equal(t, http.StatusNotFound, resp1.StatusCode)
} }
func TestConvertProxyModeWork(t *testing.T) { func TestConvertProxyModeWork(t *testing.T) {