Skip to content

Commit e8e12ee

Browse files
authored
Merge pull request #24 from webp-sh/add-log-level
Add custom log level, unsupported file returns
2 parents bc7ac93 + db8f60e commit e8e12ee

File tree

10 files changed

+82
-40
lines changed

10 files changed

+82
-40
lines changed

.travis.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ go:
66
arch:
77
- amd64
88
- arm64
9-
- ppc64le
109

1110
os:
1211
- windows

config.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
"IMG_PATH": "/path/to/pics",
66
"EXHAUST_PATH": "",
77
"ALLOWED_TYPES": ["jpg","png","jpeg","bmp","gif"]
8-
}
8+
}

encoder.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,24 @@ package main
33
import (
44
"bytes"
55
"errors"
6-
"fmt"
7-
"github.com/chai2010/webp"
8-
"golang.org/x/image/bmp"
96
"image"
107
"image/gif"
118
"image/jpeg"
129
"image/png"
1310
"io/ioutil"
14-
"log"
1511
"path"
1612
"strings"
13+
14+
log "github.com/sirupsen/logrus"
15+
16+
"github.com/chai2010/webp"
17+
"golang.org/x/image/bmp"
1718
)
1819

1920
func WebpEncoder(p1, p2 string, quality float32, Log bool, c chan int) (err error) {
2021
// if convert fails, return error; success nil
22+
23+
log.Debugf("target: %s with quality of %f", path.Base(p1), quality)
2124
var buf bytes.Buffer
2225
var img image.Image
2326

@@ -36,30 +39,31 @@ func WebpEncoder(p1, p2 string, quality float32, Log bool, c chan int) (err erro
3639
img, _ = bmp.Decode(bytes.NewReader(data))
3740
} else if strings.Contains(contentType, "gif") {
3841
// TODO: need to support animated webp
42+
log.Warn("Gif support is not perfect!")
3943
img, _ = gif.Decode(bytes.NewReader(data))
4044
}
4145

4246
if img == nil {
4347
msg := "image file " + path.Base(p1) + " is corrupted or not supported"
44-
log.Println(msg)
48+
log.Debug(msg)
4549
err = errors.New(msg)
4650
ChanErr(c)
4751
return
4852
}
4953

5054
if err = webp.Encode(&buf, img, &webp.Options{Lossless: false, Quality: quality}); err != nil {
51-
log.Println(err)
55+
log.Error(err)
5256
ChanErr(c)
5357
return
5458
}
5559
if err = ioutil.WriteFile(p2, buf.Bytes(), 0755); err != nil {
56-
log.Println(err)
60+
log.Error(err)
5761
ChanErr(c)
5862
return
5963
}
6064

6165
if Log {
62-
fmt.Printf("Save to %s ok\n", p2)
66+
log.Info("Save to " + p2 + " ok!\n")
6367
}
6468

6569
ChanErr(c)

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ go 1.13
55
require (
66
github.com/chai2010/webp v1.1.0
77
github.com/gofiber/fiber v1.4.0
8+
github.com/sirupsen/logrus v1.4.2
89
golang.org/x/image v0.0.0-20200119044424-58c23975cae1
910
)

helper.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"fmt"
5+
log "github.com/sirupsen/logrus"
56
"net/http"
67
"os"
78
"path"
@@ -38,14 +39,15 @@ func ImageExists(filename string) bool {
3839
if os.IsNotExist(err) {
3940
return false
4041
}
42+
log.Debugf("file %s exists!", filename)
4143
return !info.IsDir()
4244
}
4345

4446
func GenWebpAbs(RawImagePath string, ExhaustPath string, ImgFilename string, reqURI string) (string, string) {
4547
// get file mod time
4648
STAT, err := os.Stat(RawImagePath)
4749
if err != nil {
48-
fmt.Println(err.Error())
50+
log.Error(err.Error())
4951
}
5052
ModifiedTime := STAT.ModTime().Unix()
5153
// webpFilename: abc.jpg.png -> abc.jpg.png1582558990.webp

prefetch.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,23 @@ package main
33
import (
44
"bufio"
55
"fmt"
6-
"log"
76
"os"
87
"path"
98
"path/filepath"
109
"strconv"
1110
"strings"
11+
12+
log "github.com/sirupsen/logrus"
1213
)
1314

1415
func PrefetchImages(confImgPath string, ExhaustPath string, QUALITY string) {
15-
fmt.Println(`Prefetch will convert all your images to webp, it may take some time and consume a lot of CPU resource. Do you want to proceed(Y/n)`)
16+
fmt.Println(`Prefetch will convert all your images to webp,
17+
it may take some time and consume a lot of CPU resource. Do you want to proceed(Y/n)`)
18+
1619
reader := bufio.NewReader(os.Stdin)
1720
char, _, _ := reader.ReadRune() //y Y enter
1821
// maximum ongoing prefetch is depending on your core of CPU
19-
log.Printf("Prefetching using %d cores", jobs)
22+
log.Infof("Prefetching using %d cores", jobs)
2023
var finishChan = make(chan int, jobs)
2124
for i := 0; i < jobs; i++ {
2225
finishChan <- 0
@@ -42,7 +45,7 @@ func PrefetchImages(confImgPath string, ExhaustPath string, QUALITY string) {
4245
return nil
4346
})
4447
if err != nil {
45-
log.Println(err)
48+
log.Debug(err)
4649
}
4750
}
4851

router.go

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
package main
22

33
import (
4-
"fmt"
5-
"github.com/gofiber/fiber"
4+
log "github.com/sirupsen/logrus"
65
"os"
76
"path"
87
"path/filepath"
98
"strconv"
109
"strings"
10+
11+
"github.com/gofiber/fiber"
1112
)
1213

1314
func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY string) func(c *fiber.Ctx) {
@@ -21,9 +22,11 @@ func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY
2122
UA := c.Get("User-Agent")
2223
if strings.Contains(UA, "Safari") && !strings.Contains(UA, "Chrome") &&
2324
!strings.Contains(UA, "Firefox") {
25+
log.Info("A Safari use has arrived...")
2426
c.SendFile(RawImageAbs)
2527
return
2628
}
29+
log.Debugf("Incoming connection from %s@%s with %s", UA, c.IP(), ImgFilename)
2730

2831
// check ext
2932
// TODO: may remove this function. Check in Nginx.
@@ -39,30 +42,36 @@ func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY
3942
}
4043
}
4144
if !allowed {
42-
c.Send("File extension not allowed!")
43-
c.SendStatus(403)
45+
msg := "File extension not allowed! " + ImgFilename
46+
log.Warn(msg)
47+
c.Send(msg)
48+
if ImageExists(RawImageAbs) {
49+
c.SendFile(RawImageAbs)
50+
}
4451
return
4552
}
4653

4754
// Check the original image for existence,
4855
if !ImageExists(RawImageAbs) {
49-
c.Send("Image not found!")
56+
msg := "Image not found!"
57+
c.Send(msg)
58+
log.Warn(msg)
5059
c.SendStatus(404)
5160
return
5261
}
5362

54-
cwd, WebpAbsPath := GenWebpAbs(RawImageAbs, ExhaustPath, ImgFilename, reqURI)
63+
_, WebpAbsPath := GenWebpAbs(RawImageAbs, ExhaustPath, ImgFilename, reqURI)
5564

5665
if ImageExists(WebpAbsPath) {
5766
finalFile = WebpAbsPath
5867
} else {
5968
// we don't have abc.jpg.png1582558990.webp
6069
// delete the old pic and convert a new one.
6170
// /home/webp_server/exhaust/path/to/tsuki.jpg.1582558990.webp
62-
destHalfFile := path.Clean(path.Join(cwd, "exhaust", path.Dir(reqURI), ImgFilename))
71+
destHalfFile := path.Clean(path.Join(WebpAbsPath, path.Dir(reqURI), ImgFilename))
6372
matches, err := filepath.Glob(destHalfFile + "*")
6473
if err != nil {
65-
fmt.Println(err.Error())
74+
log.Error(err.Error())
6675
} else {
6776
// /home/webp_server/exhaust/path/to/tsuki.jpg.1582558100.webp <- older ones will be removed
6877
// /home/webp_server/exhaust/path/to/tsuki.jpg.1582558990.webp <- keep the latest one
@@ -79,7 +88,7 @@ func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY
7988
err = WebpEncoder(RawImageAbs, WebpAbsPath, float32(q), true, nil)
8089

8190
if err != nil {
82-
fmt.Println(err)
91+
log.Error(err)
8392
c.SendStatus(400)
8493
c.Send("Bad file!")
8594
return

scripts/webp_server.spec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
Name: webp-server
2-
Version: 0.0.4
2+
Version: 0.1.1
33
Release: 1%{?dist}
44
Summary: Go version of WebP Server. A tool that will serve your JPG/PNGs as WebP format with compression, on-the-fly.
55

update.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,18 @@ import (
44
"encoding/json"
55
"fmt"
66
"io/ioutil"
7-
"log"
87
"net/http"
98
"os"
109
"path"
1110
"runtime"
11+
12+
log "github.com/sirupsen/logrus"
1213
)
1314

1415
func autoUpdate() {
1516
defer func() {
1617
if err := recover(); err != nil {
17-
log.Println("Download error.", err)
18+
log.Error("Download error.", err)
1819
}
1920
}()
2021

@@ -23,16 +24,16 @@ func autoUpdate() {
2324
TagName string `json:"tag_name"`
2425
}
2526
var res Result
27+
log.Debugf("Requesting to %s", api)
2628
resp1, _ := http.Get(api)
2729
data1, _ := ioutil.ReadAll(resp1.Body)
2830
_ = json.Unmarshal(data1, &res)
29-
3031
var gitVersion = res.TagName
3132

3233
if gitVersion > version {
33-
log.Printf("Time to update! New version %s found!", gitVersion)
34+
log.Infof("Time to update! New version %s found", gitVersion)
3435
} else {
35-
log.Println("No new version found.")
36+
log.Debug("No new version found.")
3637
return
3738
}
3839

@@ -41,11 +42,10 @@ func autoUpdate() {
4142
filename += ".exe"
4243
}
4344
var releaseUrl = "https://github.com/webp-sh/webp_server_go/releases/latest/download/" + filename
44-
log.Println("Downloading binary...")
45+
log.Info("Downloading binary to update...")
4546
resp, _ := http.Get(releaseUrl)
4647
if resp.StatusCode != 200 {
47-
log.Printf("%s-%s not found on release. "+
48-
"Contact developers to supply your version", runtime.GOOS, runtime.GOARCH)
48+
log.Debug("%s-%s not found on release.", runtime.GOOS, runtime.GOARCH)
4949
return
5050
}
5151
data, _ := ioutil.ReadAll(resp.Body)
@@ -54,7 +54,7 @@ func autoUpdate() {
5454
err := ioutil.WriteFile(path.Join("update", filename), data, 0755)
5555

5656
if err == nil {
57-
log.Println("Update complete. Please find your binary from update directory.")
57+
log.Info("Update complete. Please find your binary from update directory.")
5858
}
5959
_ = resp.Body.Close()
6060
}

webp-server.go

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import (
44
"encoding/json"
55
"flag"
66
"fmt"
7-
"log"
87
"os"
98
"path"
109
"runtime"
1110

1211
"github.com/gofiber/fiber"
12+
log "github.com/sirupsen/logrus"
1313
)
1414

1515
type Config struct {
@@ -21,13 +21,14 @@ type Config struct {
2121
ExhaustPath string `json:"EXHAUST_PATH"`
2222
}
2323

24-
const version = "0.1.0"
24+
const version = "0.1.1"
2525

2626
var configPath string
2727
var prefetch bool
2828
var jobs int
2929
var dumpConfig bool
3030
var dumpSystemd bool
31+
var verboseMode bool
3132

3233
const sampleConfig = `
3334
{
@@ -36,7 +37,7 @@ const sampleConfig = `
3637
"QUALITY": "80",
3738
"IMG_PATH": "/path/to/pics",
3839
"EXHAUST_PATH": "",
39-
"ALLOWED_TYPES": ["jpg","png","jpeg","bmp","gif"]
40+
"ALLOWED_TYPES": ["jpg","png","jpeg","bmp"]
4041
}`
4142
const sampleSystemd = `
4243
[Unit]
@@ -54,7 +55,6 @@ ExecReload=/bin/kill -HUP $MAINPID
5455
Restart=always
5556
RestartSec=3s
5657
57-
5858
[Install]
5959
WantedBy=multi-user.target`
6060

@@ -67,6 +67,11 @@ func loadConfig(path string) Config {
6767
defer jsonObject.Close()
6868
decoder := json.NewDecoder(jsonObject)
6969
_ = decoder.Decode(&config)
70+
_, err = os.Stat(config.ImgPath)
71+
if err != nil {
72+
log.Fatalf("Your image path %s is incorrect.Please check and confirm.", config.ImgPath)
73+
}
74+
7075
return config
7176
}
7277

@@ -76,7 +81,27 @@ func init() {
7681
flag.IntVar(&jobs, "jobs", runtime.NumCPU(), "Prefetch thread, default is all.")
7782
flag.BoolVar(&dumpConfig, "dump-config", false, "Print sample config.json")
7883
flag.BoolVar(&dumpSystemd, "dump-systemd", false, "Print sample systemd service file.")
84+
flag.BoolVar(&verboseMode, "v", false, "Verbose, print out debug info.")
7985
flag.Parse()
86+
// Logrus
87+
log.SetOutput(os.Stdout)
88+
log.SetReportCaller(true)
89+
Formatter := &log.TextFormatter{
90+
EnvironmentOverrideColors: true,
91+
FullTimestamp: true,
92+
TimestampFormat: "2006-01-02 15:04:05",
93+
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
94+
return fmt.Sprintf("[%s()]", f.Function), ""
95+
},
96+
}
97+
log.SetFormatter(Formatter)
98+
99+
if verboseMode {
100+
log.SetLevel(log.DebugLevel)
101+
log.Debug("Debug mode is enable!")
102+
} else {
103+
log.SetLevel(log.InfoLevel)
104+
}
80105
}
81106

82107
func main() {
@@ -116,8 +141,7 @@ func main() {
116141
ListenAddress := HOST + ":" + PORT
117142

118143
// Server Info
119-
ServerInfo := "WebP Server " + version + " is running at " + ListenAddress
120-
fmt.Println(ServerInfo)
144+
log.Infof("WebP Server %s %s", version, ListenAddress)
121145

122146
app.Get("/*", Convert(confImgPath, ExhaustPath, AllowedTypes, QUALITY))
123147
app.Listen(ListenAddress)

0 commit comments

Comments
 (0)