Add golangci/golangci-lint (#181)

* Add golangci/golangci-lint

* Fix golanglint
This commit is contained in:
Nova Kwok 2023-03-18 22:24:06 +08:00 committed by GitHub
parent 71464b40a1
commit dc4da7bae4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 94 additions and 19 deletions

1
.gitignore vendored
View File

@ -4,6 +4,7 @@
*.dll *.dll
*.so *.so
*.dylib *.dylib
tools/bin
# Test binary, built with `go test -c` # Test binary, built with `go test -c`
*.test *.test

43
.golangci.yml Normal file
View File

@ -0,0 +1,43 @@
run:
timeout: 10m
linters:
disable-all: true
enable:
- misspell
- ineffassign
- typecheck
- unused
- gosimple
- errcheck
- staticcheck
- stylecheck
- gosec
- asciicheck
- bodyclose
- exportloopref
- rowserrcheck
- unconvert
- makezero
- durationcheck
- prealloc
- predeclared
linters-settings:
staticcheck:
checks: ["S1002","S1004","S1007","S1009","S1010","S1012","S1019","S1020","S1021","S1024","S1030","SA2*","SA3*","SA4009","SA5*","SA6000","SA6001","SA6005", "-SA2002"]
stylecheck:
checks: ["-ST1003"]
gosec:
severity: "low"
confidence: "low"
excludes:
- G101
- G107
issues:
exclude-rules:
- path: _test\.go
linters:
- errcheck
- gosec
- rowserrcheck
- makezero

View File

@ -19,7 +19,19 @@ all:
make clean make clean
./scripts/build.sh $(OS) $(ARCH) ./scripts/build.sh $(OS) $(ARCH)
test: tools-dir:
mkdir -p tools/bin
install-staticcheck: tools-dir
GOBIN=`pwd`/tools/bin go install honnef.co/go/tools/cmd/staticcheck@latest
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b ./tools/bin v1.51.2
static-check: install-staticcheck
#S1000,SA1015,SA4006,SA4011,S1023,S1034,ST1003,ST1005,ST1016,ST1020,ST1021
tools/bin/staticcheck -checks all,-ST1000 ./...
GO111MODULE=on tools/bin/golangci-lint run -v $$($(PACKAGE_DIRECTORIES)) --config .golangci.yml
test: static-check
go test -v -coverprofile=coverage.txt -covermode=atomic go test -v -coverprofile=coverage.txt -covermode=atomic
clean: clean:

View File

@ -23,7 +23,7 @@ var (
remoteRaw = "remote-raw" remoteRaw = "remote-raw"
config Config config Config
version = "0.5.0" version = "0.5.0"
releaseUrl = "https://github.com/webp-sh/webp_server_go/releases/latest/download/" releaseURL = "https://github.com/webp-sh/webp_server_go/releases/latest/download/"
) )
const ( const (

View File

@ -55,6 +55,9 @@ func convertImage(raw, optimized, itype string) {
//we need to create dir first //we need to create dir first
err = os.MkdirAll(path.Dir(optimized), 0755) err = os.MkdirAll(path.Dir(optimized), 0755)
if err != nil {
log.Error(err.Error())
}
//q, _ := strconv.ParseFloat(config.Quality, 32) //q, _ := strconv.ParseFloat(config.Quality, 32)
switch itype { switch itype {
@ -137,7 +140,7 @@ func webpEncoder(p1, p2 string, quality float32) error {
log.Warnf("Can't encode source image: %v to WebP", err) log.Warnf("Can't encode source image: %v to WebP", err)
} }
if err := os.WriteFile(p2, buf.Bytes(), 0644); err != nil { if err := os.WriteFile(p2, buf.Bytes(), 0600); err != nil {
log.Error(err) log.Error(err)
return err return err
} }

View File

@ -84,12 +84,13 @@ func checkAllowedType(imgFilename string) bool {
// 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) {
res, err := http.Head(fileUrl) res, err := http.Head(fileURL)
if err != nil { if err != nil {
log.Errorln("Connection to remote error!") log.Errorln("Connection to remote error!")
return http.StatusInternalServerError, "", "" return http.StatusInternalServerError, "", ""
} }
defer res.Body.Close()
if res.StatusCode != 404 { if res.StatusCode != 404 {
etagValue := res.Header.Get("etag") etagValue := res.Header.Get("etag")
if etagValue == "" { if etagValue == "" {

View File

@ -69,10 +69,10 @@ func convert(c *fiber.Ctx) error {
var availableFiles = []string{rawImageAbs} var availableFiles = []string{rawImageAbs}
for _, v := range goodFormat { for _, v := range goodFormat {
if "avif" == v { if v == "avif" {
availableFiles = append(availableFiles, avifAbs) availableFiles = append(availableFiles, avifAbs)
} }
if "webp" == v { if v == "webp" {
availableFiles = append(availableFiles, webpAbs) availableFiles = append(availableFiles, webpAbs)
} }
} }

View File

@ -52,6 +52,7 @@ func TestServerHeaders(t *testing.T) {
// test for chrome // test for chrome
response, _ := requestToServer(url, app, chromeUA, acceptWebP) response, _ := requestToServer(url, app, chromeUA, acceptWebP)
defer response.Body.Close()
ratio := response.Header.Get("X-Compression-Rate") ratio := response.Header.Get("X-Compression-Rate")
etag := response.Header.Get("Etag") etag := response.Header.Get("Etag")
@ -60,7 +61,8 @@ func TestServerHeaders(t *testing.T) {
// test for safari // test for safari
response, _ = requestToServer(url, app, safariUA, acceptLegacy) response, _ = requestToServer(url, app, safariUA, acceptLegacy)
ratio = response.Header.Get("X-Compression-Rate") defer response.Body.Close()
// ratio = response.Header.Get("X-Compression-Rate")
etag = response.Header.Get("Etag") etag = response.Header.Get("Etag")
assert.NotEqual(t, "", etag) assert.NotEqual(t, "", etag)
@ -96,14 +98,16 @@ func TestConvert(t *testing.T) {
// test Chrome // test Chrome
for url, respType := range testChromeLink { for url, respType := range testChromeLink {
_, data := requestToServer(url, app, chromeUA, acceptWebP) resp, data := requestToServer(url, app, chromeUA, acceptWebP)
defer resp.Body.Close()
contentType := getFileContentType(data) contentType := getFileContentType(data)
assert.Equal(t, respType, contentType) assert.Equal(t, respType, contentType)
} }
// test Safari // test Safari
for url, respType := range testSafariLink { for url, respType := range testSafariLink {
_, data := requestToServer(url, app, safariUA, acceptLegacy) resp, data := requestToServer(url, app, safariUA, acceptLegacy)
defer resp.Body.Close()
contentType := getFileContentType(data) contentType := getFileContentType(data)
assert.Equal(t, respType, contentType) assert.Equal(t, respType, contentType)
} }
@ -119,12 +123,14 @@ func TestConvertNotAllowed(t *testing.T) {
// not allowed, but we have the file, this should return File extension not allowed // not allowed, but we have the file, this should return File extension not allowed
url := "http://127.0.0.1:3333/webp_server.bmp" url := "http://127.0.0.1:3333/webp_server.bmp"
_, data := requestToServer(url, app, chromeUA, acceptWebP) resp, data := requestToServer(url, app, chromeUA, acceptWebP)
defer resp.Body.Close()
assert.Contains(t, string(data), "File extension not allowed") assert.Contains(t, string(data), "File extension not allowed")
// not allowed, random file // not allowed, random file
url = url + "hagdgd" url = url + "hagdgd"
_, data = requestToServer(url, app, chromeUA, acceptWebP) resp, data = requestToServer(url, app, chromeUA, acceptWebP)
defer resp.Body.Close()
assert.Contains(t, string(data), "File extension not allowed") assert.Contains(t, string(data), "File extension not allowed")
} }
@ -139,6 +145,7 @@ func TestConvertProxyModeBad(t *testing.T) {
// this is local random image, should be 500 // this is local random image, should be 500
url := "http://127.0.0.1:3333/webp_8888server.bmp" url := "http://127.0.0.1:3333/webp_8888server.bmp"
resp, _ := requestToServer(url, app, chromeUA, acceptWebP) resp, _ := requestToServer(url, app, chromeUA, acceptWebP)
defer resp.Body.Close()
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
} }
@ -154,11 +161,13 @@ func TestConvertProxyModeWork(t *testing.T) {
url := "https://webp.sh/images/cover.jpg" url := "https://webp.sh/images/cover.jpg"
resp, data := requestToServer(url, app, chromeUA, acceptWebP) resp, data := requestToServer(url, app, chromeUA, acceptWebP)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "image/webp", getFileContentType(data)) assert.Equal(t, "image/webp", getFileContentType(data))
// test proxyMode with Safari // test proxyMode with Safari
resp, data = requestToServer(url, app, safariUA, acceptLegacy) resp, data = requestToServer(url, app, safariUA, acceptLegacy)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "image/jpeg", getFileContentType(data)) assert.Equal(t, "image/jpeg", getFileContentType(data))
} }
@ -171,8 +180,9 @@ func TestConvertBigger(t *testing.T) {
app.Get("/*", convert) app.Get("/*", convert)
url := "http://127.0.0.1:3333/big.jpg" url := "http://127.0.0.1:3333/big.jpg"
response, data := requestToServer(url, app, chromeUA, acceptWebP) resp, data := requestToServer(url, app, chromeUA, acceptWebP)
assert.Equal(t, "image/jpeg", response.Header.Get("content-type")) defer resp.Body.Close()
assert.Equal(t, "image/jpeg", resp.Header.Get("content-type"))
assert.Equal(t, "image/jpeg", getFileContentType(data)) assert.Equal(t, "image/jpeg", getFileContentType(data))
_ = os.RemoveAll(config.ExhaustPath) _ = os.RemoveAll(config.ExhaustPath)
} }

View File

@ -25,7 +25,11 @@ func autoUpdate() {
} }
var res Result var res Result
log.Debugf("Requesting to %s", api) log.Debugf("Requesting to %s", api)
resp1, _ := http.Get(api) resp1, err := http.Get(api)
if err != nil {
log.Errorf("Error requesting to %s", api)
}
defer resp1.Body.Close()
data1, _ := io.ReadAll(resp1.Body) data1, _ := io.ReadAll(resp1.Body)
_ = json.Unmarshal(data1, &res) _ = json.Unmarshal(data1, &res)
var gitVersion = res.TagName var gitVersion = res.TagName
@ -42,13 +46,13 @@ func autoUpdate() {
filename += ".exe" filename += ".exe"
} }
log.Info("Downloading binary to update...") log.Info("Downloading binary to update...")
resp, _ := http.Get(releaseUrl + filename) resp, _ := http.Get(releaseURL + filename)
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Debugf("%s-%s not found on release.", runtime.GOOS, runtime.GOARCH) log.Debugf("%s-%s not found on release.", runtime.GOOS, runtime.GOARCH)
return return
} }
err := update.Apply(resp.Body, update.Options{}) err = update.Apply(resp.Body, update.Options{})
if err != nil { if err != nil {
// error handling // error handling
log.Errorf("Update error. %v", err) log.Errorf("Update error. %v", err)

View File

@ -5,9 +5,10 @@
package main package main
import ( import (
"github.com/stretchr/testify/assert"
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestNormalAutoUpdate(t *testing.T) { func TestNormalAutoUpdate(t *testing.T) {
@ -21,7 +22,7 @@ func TestNormalAutoUpdate(t *testing.T) {
func Test404AutoUpdate(t *testing.T) { func Test404AutoUpdate(t *testing.T) {
version = "0.0.1" version = "0.0.1"
dir := "./update" dir := "./update"
releaseUrl = releaseUrl + "a" releaseURL = releaseURL + "a"
autoUpdate() autoUpdate()
assert.Equal(t, int64(0), fileCount(dir)) assert.Equal(t, int64(0), fileCount(dir))
_ = os.RemoveAll(dir) _ = os.RemoveAll(dir)