fix: error from golangci-lint tool (#623)

This commit is contained in:
Bo-Yi Wu 2021-08-03 14:44:00 +08:00 committed by GitHub
parent 349c0c8c1d
commit 0a8d801380
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 74 additions and 164 deletions

View File

@ -7,29 +7,11 @@ platform:
arch: amd64 arch: amd64
steps: steps:
- name: vet
pull: always
image: golang:1.16
commands:
- make vet
volumes:
- name: gopath
path: /go
- name: lint - name: lint
pull: always pull: always
image: golang:1.16 image: golangci/golangci-lint:v1.41.1
commands: commands:
- make lint - golangci-lint run -v
volumes:
- name: gopath
path: /go
- name: misspell
pull: always
image: golang:1.16
commands:
- make misspell-check
volumes: volumes:
- name: gopath - name: gopath
path: /go path: /go
@ -127,19 +109,6 @@ steps:
commands: commands:
- ./release/linux/amd64/gorush --help - ./release/linux/amd64/gorush --help
- name: dryrun
pull: always
image: plugins/docker:linux-amd64
settings:
cache_from: appleboy/gorush
dockerfile: docker/Dockerfile.linux.amd64
dry_run: true
repo: appleboy/gorush
tags: linux-amd64
when:
event:
- pull_request
- name: publish - name: publish
pull: always pull: always
image: plugins/docker:linux-amd64 image: plugins/docker:linux-amd64
@ -206,19 +175,6 @@ steps:
commands: commands:
- ./release/linux/arm64/gorush --help - ./release/linux/arm64/gorush --help
- name: dryrun
pull: always
image: plugins/docker:linux-arm64
settings:
cache_from: appleboy/gorush
dockerfile: docker/Dockerfile.linux.arm64
dry_run: true
repo: appleboy/gorush
tags: linux-arm64
when:
event:
- pull_request
- name: publish - name: publish
pull: always pull: always
image: plugins/docker:linux-arm64 image: plugins/docker:linux-arm64
@ -285,19 +241,6 @@ steps:
commands: commands:
- ./release/linux/arm/gorush --help - ./release/linux/arm/gorush --help
- name: dryrun
pull: always
image: plugins/docker:linux-arm
settings:
cache_from: appleboy/gorush
dockerfile: docker/Dockerfile.linux.arm
dry_run: true
repo: appleboy/gorush
tags: linux-arm
when:
event:
- pull_request
- name: publish - name: publish
pull: always pull: always
image: plugins/docker:linux-arm image: plugins/docker:linux-arm

View File

@ -15,12 +15,9 @@ import (
var ( var (
green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109}) green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109}) yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109}) red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109}) blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
reset = string([]byte{27, 91, 48, 109}) reset = string([]byte{27, 91, 48, 109})
) )

17
main.go
View File

@ -219,7 +219,9 @@ func main() {
return return
} }
notify.PushToAndroid(req, cfg) if _, err := notify.PushToAndroid(req, cfg); err != nil {
return
}
return return
} }
@ -252,7 +254,9 @@ func main() {
return return
} }
notify.PushToHuawei(req, cfg) if _, err := notify.PushToHuawei(req, cfg); err != nil {
return
}
return return
} }
@ -292,7 +296,10 @@ func main() {
if err := notify.InitAPNSClient(cfg); err != nil { if err := notify.InitAPNSClient(cfg); err != nil {
return return
} }
notify.PushToIOS(req, cfg)
if _, err := notify.PushToIOS(req, cfg); err != nil {
return
}
return return
} }
@ -397,9 +404,7 @@ func main() {
// check job completely // check job completely
g.Go(func() error { g.Go(func() error {
select { <-finished
case <-finished:
}
return nil return nil
}) })

View File

@ -2,6 +2,7 @@ package notify
import ( import (
"log" "log"
"os"
"testing" "testing"
"github.com/appleboy/gorush/config" "github.com/appleboy/gorush/config"
@ -14,5 +15,5 @@ func TestMain(m *testing.M) {
log.Fatal(err) log.Fatal(err)
} }
m.Run() os.Exit(m.Run())
} }

View File

@ -96,8 +96,8 @@ func TestIOSNotificationStructure(t *testing.T) {
soundVolume, _ := jsonparser.GetFloat(data, "aps", "sound", "volume") soundVolume, _ := jsonparser.GetFloat(data, "aps", "sound", "volume")
contentAvailable, _ := jsonparser.GetInt(data, "aps", "content-available") contentAvailable, _ := jsonparser.GetInt(data, "aps", "content-available")
category, _ := jsonparser.GetString(data, "aps", "category") category, _ := jsonparser.GetString(data, "aps", "category")
key1 := dat["key1"].(interface{}) key1 := dat["key1"]
key2 := dat["key2"].(interface{}) key2 := dat["key2"]
aps := dat["aps"].(map[string]interface{}) aps := dat["aps"].(map[string]interface{})
urlArgs := aps["url-args"].([]interface{}) urlArgs := aps["url-args"].([]interface{})
@ -732,7 +732,9 @@ func TestPushToIOS(t *testing.T) {
} }
// send fail // send fail
PushToIOS(req, cfg) resp, err := PushToIOS(req, cfg)
assert.Nil(t, err)
assert.Len(t, resp.Logs, 2)
} }
func TestApnsHostFromRequest(t *testing.T) { func TestApnsHostFromRequest(t *testing.T) {

View File

@ -46,7 +46,9 @@ func TestPushToAndroidWrongToken(t *testing.T) {
} }
// Android Success count: 0, Failure count: 2 // Android Success count: 0, Failure count: 2
PushToAndroid(req, cfg) resp, err := PushToAndroid(req, cfg)
assert.Nil(t, err)
assert.Len(t, resp.Logs, 2)
} }
func TestPushToAndroidRightTokenForJSONLog(t *testing.T) { func TestPushToAndroidRightTokenForJSONLog(t *testing.T) {
@ -65,7 +67,9 @@ func TestPushToAndroidRightTokenForJSONLog(t *testing.T) {
Message: "Welcome", Message: "Welcome",
} }
PushToAndroid(req, cfg) resp, err := PushToAndroid(req, cfg)
assert.Nil(t, err)
assert.Len(t, resp.Logs, 0)
} }
func TestPushToAndroidRightTokenForStringLog(t *testing.T) { func TestPushToAndroidRightTokenForStringLog(t *testing.T) {
@ -82,7 +86,9 @@ func TestPushToAndroidRightTokenForStringLog(t *testing.T) {
Message: "Welcome", Message: "Welcome",
} }
PushToAndroid(req, cfg) resp, err := PushToAndroid(req, cfg)
assert.Nil(t, err)
assert.Len(t, resp.Logs, 0)
} }
func TestOverwriteAndroidAPIKey(t *testing.T) { func TestOverwriteAndroidAPIKey(t *testing.T) {
@ -200,7 +206,10 @@ func TestCheckAndroidMessage(t *testing.T) {
TimeToLive: &timeToLive, TimeToLive: &timeToLive,
} }
PushToAndroid(req, cfg) // the message's TimeToLive field must be an integer between 0 and 2419200 (4 weeks)
resp, err := PushToAndroid(req, cfg)
assert.NotNil(t, err)
assert.Nil(t, resp)
} }
func TestAndroidNotificationStructure(t *testing.T) { func TestAndroidNotificationStructure(t *testing.T) {

View File

@ -7,40 +7,12 @@
arch: 'amd64', arch: 'amd64',
}, },
steps: [ steps: [
{
name: 'vet',
image: 'golang:1.16',
pull: 'always',
commands: [
'make vet',
],
volumes: [
{
name: 'gopath',
path: '/go',
},
],
},
{ {
name: 'lint', name: 'lint',
image: 'golang:1.16', image: 'golangci/golangci-lint:v1.41.1',
pull: 'always', pull: 'always',
commands: [ commands: [
'make lint', 'golangci-lint run -v',
],
volumes: [
{
name: 'gopath',
path: '/go',
},
],
},
{
name: 'misspell',
image: 'golang:1.16',
pull: 'always',
commands: [
'make misspell-check',
], ],
volumes: [ volumes: [
{ {
@ -190,22 +162,6 @@
'./release/' + os + '/' + arch + '/' + name + ' --help', './release/' + os + '/' + arch + '/' + name + ' --help',
], ],
}, },
{
name: 'dryrun',
image: 'plugins/docker:' + os + '-' + arch,
pull: 'always',
settings: {
daemon_off: false,
dry_run: true,
tags: os + '-' + arch,
dockerfile: 'docker/Dockerfile.' + os + '.' + arch,
repo: 'appleboy/' + name,
cache_from: 'appleboy/' + name,
},
when: {
event: [ 'pull_request' ],
},
},
{ {
name: 'publish', name: 'publish',
image: 'plugins/docker:' + os + '-' + arch, image: 'plugins/docker:' + os + '-' + arch,

View File

@ -284,7 +284,7 @@ func handleNotification(ctx context.Context, cfg *config.ConfYaml, req notify.Re
if core.IsLocalQueue(core.Queue(cfg.Queue.Engine)) && cfg.Core.Sync { if core.IsLocalQueue(core.Queue(cfg.Queue.Engine)) && cfg.Core.Sync {
func(msg *notify.PushNotification, cfg *config.ConfYaml) { func(msg *notify.PushNotification, cfg *config.ConfYaml) {
q.QueueTask(func(ctx context.Context) error { if err := q.QueueTask(func(ctx context.Context) error {
defer wg.Done() defer wg.Done()
resp, err := notify.SendNotification(msg, cfg) resp, err := notify.SendNotification(msg, cfg)
if err != nil { if err != nil {
@ -292,19 +292,17 @@ func handleNotification(ctx context.Context, cfg *config.ConfYaml, req notify.Re
} }
// add log // add log
for _, v := range resp.Logs { logs = append(logs, resp.Logs...)
logs = append(logs, v)
}
return nil return nil
}) }); err != nil {
logx.LogError.Error(err)
}
}(notification, cfg) }(notification, cfg)
} else if err := q.Queue(notification); err != nil { } else if err := q.Queue(notification); err != nil {
resp := markFailedNotification(cfg, notification, "max capacity reached") resp := markFailedNotification(cfg, notification, "max capacity reached")
// add log // add log
for _, v := range resp { logs = append(logs, resp...)
logs = append(logs, v)
}
wg.Done() wg.Done()
} }

View File

@ -82,13 +82,11 @@ func RunHTTPServer(ctx context.Context, cfg *config.ConfYaml, q *queue.Queue, s
func listenAndServe(ctx context.Context, s *http.Server, cfg *config.ConfYaml) error { func listenAndServe(ctx context.Context, s *http.Server, cfg *config.ConfYaml) error {
var g errgroup.Group var g errgroup.Group
g.Go(func() error { g.Go(func() error {
select { <-ctx.Done()
case <-ctx.Done():
timeout := time.Duration(cfg.Core.ShutdownTimeout) * time.Second timeout := time.Duration(cfg.Core.ShutdownTimeout) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout) ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel() defer cancel()
return s.Shutdown(ctx) return s.Shutdown(ctx)
}
}) })
g.Go(func() error { g.Go(func() error {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed { if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
@ -102,13 +100,11 @@ func listenAndServe(ctx context.Context, s *http.Server, cfg *config.ConfYaml) e
func listenAndServeTLS(ctx context.Context, s *http.Server, cfg *config.ConfYaml) error { func listenAndServeTLS(ctx context.Context, s *http.Server, cfg *config.ConfYaml) error {
var g errgroup.Group var g errgroup.Group
g.Go(func() error { g.Go(func() error {
select { <-ctx.Done()
case <-ctx.Done():
timeout := time.Duration(cfg.Core.ShutdownTimeout) * time.Second timeout := time.Duration(cfg.Core.ShutdownTimeout) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout) ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel() defer cancel()
return s.Shutdown(ctx) return s.Shutdown(ctx)
}
}) })
g.Go(func() error { g.Go(func() error {
if err := s.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed { if err := s.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {

View File

@ -59,7 +59,7 @@ func TestMain(m *testing.M) {
q.Wait() q.Wait()
}() }()
m.Run() os.Exit(m.Run())
} }
func initTest() *config.ConfYaml { func initTest() *config.ConfYaml {
@ -232,7 +232,6 @@ func TestRootHandler(t *testing.T) {
assert.Equal(t, "Welcome to notification server.", value) assert.Equal(t, "Welcome to notification server.", value)
assert.Equal(t, http.StatusOK, r.Code) assert.Equal(t, http.StatusOK, r.Code)
assert.Equal(t, "application/json; charset=utf-8", r.HeaderMap.Get("Content-Type"))
}) })
} }
@ -291,7 +290,6 @@ func TestMissingNotificationsParameter(t *testing.T) {
r.POST("/api/push"). r.POST("/api/push").
Run(routerEngine(cfg, q), func(r gofight.HTTPResponse, rq gofight.HTTPRequest) { Run(routerEngine(cfg, q), func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusBadRequest, r.Code) assert.Equal(t, http.StatusBadRequest, r.Code)
assert.Equal(t, "application/json; charset=utf-8", r.HeaderMap.Get("Content-Type"))
}) })
} }

View File

@ -7,6 +7,7 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
// generate protobuffs // generate protobuffs
@ -41,7 +42,7 @@ func (c *healthClient) Check(ctx context.Context) (bool, error) {
} }
return false, nil return false, nil
} }
switch grpc.Code(err) { switch status.Code(err) {
case case
codes.Aborted, codes.Aborted,
codes.DataLoss, codes.DataLoss,

View File

@ -8,6 +8,7 @@ import (
"github.com/appleboy/gorush/rpc" "github.com/appleboy/gorush/rpc"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/status"
) )
const ( const (
@ -27,7 +28,7 @@ func main() {
for { for {
ok, err := client.Check(context.Background()) ok, err := client.Check(context.Background())
if !ok || err != nil { if !ok || err != nil {
log.Printf("can't connect grpc server: %v, code: %v\n", err, grpc.Code(err)) log.Printf("can't connect grpc server: %v, code: %v\n", err, status.Code(err))
} else { } else {
log.Println("connect the grpc server successfully") log.Println("connect the grpc server successfully")
} }

View File

@ -101,7 +101,12 @@ func (s *Server) Send(ctx context.Context, in *proto.NotificationRequest) (*prot
} }
} }
go notify.SendNotification(&notification, s.cfg) go func() {
_, err := notify.SendNotification(&notification, s.cfg)
if err != nil {
logx.LogError.Error(err)
}
}()
return &proto.NotificationReply{ return &proto.NotificationReply{
Success: true, Success: true,
@ -131,11 +136,9 @@ func RunGRPCServer(ctx context.Context, cfg *config.ConfYaml) error {
} }
logx.LogAccess.Info("gRPC server is running on " + cfg.GRPC.Port + " port.") logx.LogAccess.Info("gRPC server is running on " + cfg.GRPC.Port + " port.")
go func() { go func() {
select { <-ctx.Done()
case <-ctx.Done():
s.GracefulStop() // graceful shutdown s.GracefulStop() // graceful shutdown
logx.LogAccess.Info("shutdown the gRPC server") logx.LogAccess.Info("shutdown the gRPC server")
}
}() }()
if err = s.Serve(lis); err != nil { if err = s.Serve(lis); err != nil {
logx.LogError.Fatalln(err) logx.LogError.Fatalln(err)

View File

@ -1,6 +1,7 @@
package status package status
import ( import (
"os"
"testing" "testing"
"time" "time"
@ -10,7 +11,7 @@ import (
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
m.Run() os.Exit(m.Run())
} }
func TestStorageDriverExist(t *testing.T) { func TestStorageDriverExist(t *testing.T) {
@ -76,7 +77,7 @@ func TestStatForRedisEngine(t *testing.T) {
err := InitAppStatus(cfg) err := InitAppStatus(cfg)
assert.Nil(t, err) assert.Nil(t, err)
StatStorage.Init() assert.Nil(t, StatStorage.Init())
StatStorage.Reset() StatStorage.Reset()
StatStorage.AddTotalCount(100) StatStorage.AddTotalCount(100)

View File

@ -1,7 +1,6 @@
package badger package badger
import ( import (
"fmt"
"log" "log"
"os" "os"
"strconv" "strconv"
@ -84,7 +83,7 @@ func (s *Storage) getBadger(key string, count *int64) {
return err return err
} }
i, err := strconv.ParseInt(fmt.Sprintf("%s", val), 10, 64) i, err := strconv.ParseInt(string(val), 10, 64)
if err != nil { if err != nil {
return err return err
} }