Browse Source

workflows: enable golangci-lint (#5998)

* Create golint.yml

* Update golint.yml

* Update golint.yml

* Fix errcheck

* Fix gosimple

* Fix staticcheck
ᴜɴᴋɴᴡᴏɴ 4 years ago
parent
commit
5843038a08

+ 9 - 0
.github/workflows/golint.yml

@@ -0,0 +1,9 @@
+name: golint
+on: [pull_request]
+jobs:
+  build:
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@v2
+    - name: Run golangci-lint
+      uses: actions-contrib/golangci-lint@v1

+ 1 - 0
docker/aarch64/resin-xbuild.go

@@ -1,3 +1,4 @@
+//nolint
 package main
 
 import (

+ 1 - 0
docker/armhf/resin-xbuild.go

@@ -1,3 +1,4 @@
+//nolint
 package main
 
 import (

+ 6 - 2
internal/cmd/admin.go

@@ -146,7 +146,9 @@ func runCreateUser(c *cli.Context) error {
 		return errors.Wrap(err, "init configuration")
 	}
 
-	db.SetEngine()
+	if err = db.SetEngine(); err != nil {
+		return errors.Wrap(err, "set engine")
+	}
 
 	if err := db.CreateUser(&db.User{
 		Name:     c.String("name"),
@@ -169,7 +171,9 @@ func adminDashboardOperation(operation func() error, successMessage string) func
 			return errors.Wrap(err, "init configuration")
 		}
 
-		db.SetEngine()
+		if err = db.SetEngine(); err != nil {
+			return errors.Wrap(err, "set engine")
+		}
 
 		if err := operation(); err != nil {
 			functionName := runtime.FuncForPC(reflect.ValueOf(operation).Pointer()).Name()

+ 3 - 1
internal/cmd/backup.go

@@ -52,7 +52,9 @@ func runBackup(c *cli.Context) error {
 		return errors.Wrap(err, "init configuration")
 	}
 
-	db.SetEngine()
+	if err = db.SetEngine(); err != nil {
+		return errors.Wrap(err, "set engine")
+	}
 
 	tmpDir := c.String("tempdir")
 	if !com.IsExist(tmpDir) {

+ 2 - 2
internal/cmd/cmd.go

@@ -25,7 +25,7 @@ func boolFlag(name, usage string) cli.BoolFlag {
 	}
 }
 
-//nolint:deadcode
+//nolint:deadcode,unused
 func intFlag(name string, value int, usage string) cli.IntFlag {
 	return cli.IntFlag{
 		Name:  name,
@@ -34,7 +34,7 @@ func intFlag(name string, value int, usage string) cli.IntFlag {
 	}
 }
 
-//nolint:deadcode
+//nolint:deadcode,unused
 func durationFlag(name string, value time.Duration, usage string) cli.DurationFlag {
 	return cli.DurationFlag{
 		Name:  name,

+ 6 - 6
internal/cmd/import.go

@@ -61,7 +61,7 @@ func runImportLocale(c *cli.Context) error {
 
 	now := time.Now()
 
-	line := make([]byte, 0, 100)
+	var line []byte
 	badChars := []byte(`="`)
 	escapedQuotes := []byte(`\"`)
 	regularQuotes := []byte(`"`)
@@ -97,15 +97,15 @@ func runImportLocale(c *cli.Context) error {
 				line = append(line[:idx+1], line[idx+2:len(line)-1]...)
 				line = bytes.Replace(line, escapedQuotes, regularQuotes, -1)
 			}
-			tw.Write(line)
-			tw.WriteString("\n")
+			_, _ = tw.Write(line)
+			_, _ = tw.WriteString("\n")
 		}
-		sr.Close()
-		tw.Close()
+		_ = sr.Close()
+		_ = tw.Close()
 
 		// Modification time of files from Crowdin often ahead of current,
 		// so we need to set back to current.
-		os.Chtimes(target, now, now)
+		_ = os.Chtimes(target, now, now)
 	}
 
 	fmt.Println("Locale files has been successfully imported!")

+ 3 - 1
internal/cmd/restore.go

@@ -99,7 +99,9 @@ func runRestore(c *cli.Context) error {
 		return errors.Wrap(err, "init configuration")
 	}
 
-	db.SetEngine()
+	if err = db.SetEngine(); err != nil {
+		return errors.Wrap(err, "set engine")
+	}
 
 	// Database
 	dbDir := path.Join(archivePath, "db")

+ 1 - 1
internal/db/comment.go

@@ -239,7 +239,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
 			attachments[i].IssueID = opts.Issue.ID
 			attachments[i].CommentID = comment.ID
 			// No assign value could be 0, so ignore AllCols().
-			if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
+			if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
 				return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
 			}
 		}

+ 1 - 1
internal/db/issue.go

@@ -738,7 +738,7 @@ func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
 
 		for i := 0; i < len(attachments); i++ {
 			attachments[i].IssueID = opts.Issue.ID
-			if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
+			if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
 				return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
 			}
 		}

+ 1 - 1
internal/db/migrations/migrations.go

@@ -337,7 +337,7 @@ func convertDateToUnix(x *xorm.Engine) (err error) {
 		offset := 0
 		for {
 			beans := make([]*Bean, 0, 100)
-			if err = x.Sql(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d",
+			if err = x.SQL(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d",
 				table.name, offset)).Find(&beans); err != nil {
 				return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
 			}

+ 1 - 1
internal/db/migrations/v16.go

@@ -37,7 +37,7 @@ func updateRepositorySizes(x *xorm.Engine) (err error) {
 	offset := 0
 	for {
 		repos := make([]*Repository, 0, 10)
-		if err = x.Sql(fmt.Sprintf("SELECT * FROM `repository` ORDER BY id ASC LIMIT 10 OFFSET %d", offset)).
+		if err = x.SQL(fmt.Sprintf("SELECT * FROM `repository` ORDER BY id ASC LIMIT 10 OFFSET %d", offset)).
 			Find(&repos); err != nil {
 			return fmt.Errorf("select repos [offset: %d]: %v", offset, err)
 		}

+ 9 - 6
internal/db/models.go

@@ -151,8 +151,8 @@ func getEngine() (*xorm.Engine, error) {
 	return xorm.NewEngine(conf.Database.Type, connStr)
 }
 
-func NewTestEngine(x *xorm.Engine) (err error) {
-	x, err = getEngine()
+func NewTestEngine() error {
+	x, err := getEngine()
 	if err != nil {
 		return fmt.Errorf("connect to database: %v", err)
 	}
@@ -260,8 +260,11 @@ type Version struct {
 }
 
 // DumpDatabase dumps all data from database to file system in JSON format.
-func DumpDatabase(dirPath string) (err error) {
-	os.MkdirAll(dirPath, os.ModePerm)
+func DumpDatabase(dirPath string) error {
+	if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
+		return err
+	}
+
 	// Purposely create a local variable to not modify global variable
 	tables := append(tables, new(Version))
 	for _, table := range tables {
@@ -275,10 +278,10 @@ func DumpDatabase(dirPath string) (err error) {
 		if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
 			return jsoniter.NewEncoder(f).Encode(bean)
 		}); err != nil {
-			f.Close()
+			_ = f.Close()
 			return fmt.Errorf("dump table '%s': %v", tableName, err)
 		}
-		f.Close()
+		_ = f.Close()
 	}
 	return nil
 }

+ 1 - 3
internal/db/org.go

@@ -131,7 +131,7 @@ func CreateOrganization(org, owner *User) (err error) {
 	if _, err = sess.Insert(org); err != nil {
 		return fmt.Errorf("insert organization: %v", err)
 	}
-	org.GenerateRandomAvatar()
+	_ = org.GenerateRandomAvatar()
 
 	// Add initial creator to organization and owner team.
 	if _, err = sess.Insert(&OrgUser{
@@ -356,10 +356,8 @@ func AddOrgUser(orgID, uid int64) error {
 	}
 
 	if _, err := sess.Insert(ou); err != nil {
-		sess.Rollback()
 		return err
 	} else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
-		sess.Rollback()
 		return err
 	}
 

+ 0 - 2
internal/db/org_team.go

@@ -255,13 +255,11 @@ func NewTeam(t *Team) error {
 	}
 
 	if _, err = sess.Insert(t); err != nil {
-		sess.Rollback()
 		return err
 	}
 
 	// Update organization number of teams.
 	if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
-		sess.Rollback()
 		return err
 	}
 	return sess.Commit()

+ 7 - 3
internal/db/pull.go

@@ -219,8 +219,12 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
 	// Create temporary directory to store temporary copy of the base repository,
 	// and clean it up when operation finished regardless of succeed or not.
 	tmpBasePath := filepath.Join(conf.Server.AppDataPath, "tmp", "repos", com.ToStr(time.Now().Nanosecond())+".git")
-	os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm)
-	defer os.RemoveAll(filepath.Dir(tmpBasePath))
+	if err = os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil {
+		return err
+	}
+	defer func() {
+		_ = os.RemoveAll(filepath.Dir(tmpBasePath))
+	}()
 
 	// Clone the base repository to the defined temporary directory,
 	// and checks out to base branch directly.
@@ -845,7 +849,7 @@ func (pr *PullRequest) checkAndUpdateStatus() {
 // TODO: test more pull requests at same time.
 func TestPullRequests() {
 	prs := make([]*PullRequest, 0, 10)
-	x.Iterate(PullRequest{
+	_ = x.Iterate(PullRequest{
 		Status: PULL_REQUEST_STATUS_CHECKING,
 	},
 		func(idx int, bean interface{}) error {

+ 9 - 3
internal/db/repo.go

@@ -660,7 +660,9 @@ func (repo *Repository) SavePatch(index int64, patch []byte) error {
 		return fmt.Errorf("PatchPath: %v", err)
 	}
 
-	os.MkdirAll(filepath.Dir(patchPath), os.ModePerm)
+	if err = os.MkdirAll(filepath.Dir(patchPath), os.ModePerm); err != nil {
+		return err
+	}
 	if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
 		return fmt.Errorf("WriteFile: %v", err)
 	}
@@ -1017,7 +1019,9 @@ func initRepository(e Engine, repoPath string, doer *User, repo *Repository, opt
 
 	// Initialize repository according to user's choice.
 	if opts.AutoInit {
-		os.MkdirAll(tmpDir, os.ModePerm)
+		if err = os.MkdirAll(tmpDir, os.ModePerm); err != nil {
+			return err
+		}
 		defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir)
 
 		if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
@@ -1349,7 +1353,9 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
 	}
 
 	// Rename remote repository to new path and delete local copy.
-	os.MkdirAll(UserPath(newOwner.Name), os.ModePerm)
+	if err = os.MkdirAll(UserPath(newOwner.Name), os.ModePerm); err != nil {
+		return err
+	}
 	if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
 		return fmt.Errorf("rename repository directory: %v", err)
 	}

+ 9 - 3
internal/db/repo_editor.go

@@ -152,7 +152,9 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
 
 	oldFilePath := path.Join(localPath, opts.OldTreeName)
 	filePath := path.Join(localPath, opts.NewTreeName)
-	os.MkdirAll(path.Dir(filePath), os.ModePerm)
+	if err = os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil {
+		return err
+	}
 
 	// If it's meant to be a new file, make sure it doesn't exist.
 	if opts.IsNewFile {
@@ -206,7 +208,9 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
 
 	localPath := repo.LocalCopyPath()
 	filePath := path.Join(localPath, treePath)
-	os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
+	if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
+		return nil, err
+	}
 	if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
 		return nil, fmt.Errorf("write file: %v", err)
 	}
@@ -471,7 +475,9 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
 
 	localPath := repo.LocalCopyPath()
 	dirPath := path.Join(localPath, opts.TreePath)
-	os.MkdirAll(dirPath, os.ModePerm)
+	if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
+		return err
+	}
 
 	// Copy uploaded files into repository
 	for _, upload := range uploads {

+ 4 - 5
internal/db/user.go

@@ -819,7 +819,7 @@ func deleteUser(e *xorm.Session, u *User) error {
 		return fmt.Errorf("clear assignee: %v", err)
 	}
 
-	if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
+	if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
 		return fmt.Errorf("Delete: %v", err)
 	}
 
@@ -827,8 +827,8 @@ func deleteUser(e *xorm.Session, u *User) error {
 	// Note: There are something just cannot be roll back,
 	//	so just keep error logs of those operations.
 
-	os.RemoveAll(UserPath(u.Name))
-	os.Remove(u.CustomAvatarPath())
+	_ = os.RemoveAll(UserPath(u.Name))
+	_ = os.Remove(u.CustomAvatarPath())
 
 	return nil
 }
@@ -1076,8 +1076,7 @@ func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error)
 		Or("LOWER(full_name) LIKE ?", searchQuery).
 		And("type = ?", opts.Type)
 
-	var countSess xorm.Session
-	countSess = *sess
+	countSess := *sess
 	count, err := countSess.Count(new(User))
 	if err != nil {
 		return nil, 0, fmt.Errorf("Count: %v", err)

+ 2 - 2
internal/db/webhook.go

@@ -629,7 +629,7 @@ func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Pay
 				log.Error("prepareWebhooks.JSONPayload: %v", err)
 			}
 			sig := hmac.New(sha256.New, []byte(w.Secret))
-			sig.Write(data)
+			_, _ = sig.Write(data)
 			signature = hex.EncodeToString(sig.Sum(nil))
 		}
 
@@ -769,7 +769,7 @@ func (t *HookTask) deliver() {
 // TODO: shoot more hooks at same time.
 func DeliverHooks() {
 	tasks := make([]*HookTask, 0, 10)
-	x.Where("is_delivered = ?", false).Iterate(new(HookTask),
+	_ = x.Where("is_delivered = ?", false).Iterate(new(HookTask),
 		func(idx int, bean interface{}) error {
 			t := bean.(*HookTask)
 			t.deliver()

+ 11 - 11
internal/httplib/httplib.go

@@ -7,6 +7,7 @@ package httplib
 
 import (
 	"bytes"
+	"context"
 	"crypto/tls"
 	"encoding/xml"
 	"io"
@@ -271,16 +272,16 @@ func (r *Request) getResponse() (*http.Response, error) {
 					}
 					//iocopy
 					_, err = io.Copy(fileWriter, fh)
-					fh.Close()
+					_ = fh.Close()
 					if err != nil {
 						log.Fatal(err)
 					}
 				}
 				for k, v := range r.params {
-					bodyWriter.WriteField(k, v)
+					_ = bodyWriter.WriteField(k, v)
 				}
-				bodyWriter.Close()
-				pw.Close()
+				_ = bodyWriter.Close()
+				_ = pw.Close()
 			}()
 			r.Header("Content-Type", bodyWriter.FormDataContentType())
 			r.req.Body = ioutil.NopCloser(pr)
@@ -304,7 +305,7 @@ func (r *Request) getResponse() (*http.Response, error) {
 		trans = &http.Transport{
 			TLSClientConfig: r.setting.TlsClientConfig,
 			Proxy:           r.setting.Proxy,
-			Dial:            TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
+			DialContext:     TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
 		}
 	} else {
 		// if r.transport is *http.Transport then set the settings.
@@ -315,8 +316,8 @@ func (r *Request) getResponse() (*http.Response, error) {
 			if t.Proxy == nil {
 				t.Proxy = r.setting.Proxy
 			}
-			if t.Dial == nil {
-				t.Dial = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
+			if t.DialContext == nil {
+				t.DialContext = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
 			}
 		}
 	}
@@ -436,13 +437,12 @@ func (r *Request) Response() (*http.Response, error) {
 }
 
 // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
-func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
-	return func(netw, addr string) (net.Conn, error) {
+func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(ctx context.Context, net, addr string) (c net.Conn, err error) {
+	return func(ctx context.Context, netw, addr string) (net.Conn, error) {
 		conn, err := net.DialTimeout(netw, addr, cTimeout)
 		if err != nil {
 			return nil, err
 		}
-		conn.SetDeadline(time.Now().Add(rwTimeout))
-		return conn, nil
+		return conn, conn.SetDeadline(time.Now().Add(rwTimeout))
 	}
 }

+ 0 - 1
internal/route/admin/admin.go

@@ -172,7 +172,6 @@ func Operation(c *context.Context) {
 		c.Flash.Success(success)
 	}
 	c.RedirectSubpath("/admin")
-	return
 }
 
 func SendTestMail(c *context.Context) {

+ 4 - 7
internal/route/install.go

@@ -11,14 +11,12 @@ import (
 	"path/filepath"
 	"strings"
 
+	"github.com/gogs/git-module"
 	"github.com/pkg/errors"
 	"github.com/unknwon/com"
 	"gopkg.in/ini.v1"
 	"gopkg.in/macaron.v1"
 	log "unknwon.dev/clog/v2"
-	"xorm.io/xorm"
-
-	"github.com/gogs/git-module"
 
 	"gogs.io/gogs/internal/conf"
 	"gogs.io/gogs/internal/context"
@@ -240,8 +238,7 @@ func InstallPost(c *context.Context, f form.Install) {
 	}
 
 	// Set test engine.
-	var x *xorm.Engine
-	if err := db.NewTestEngine(x); err != nil {
+	if err := db.NewTestEngine(); err != nil {
 		if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
 			c.FormErr("DbType")
 			c.RenderWithErr(c.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f)
@@ -419,8 +416,8 @@ func InstallPost(c *context.Context, f form.Install) {
 		}
 
 		// Auto-login for admin
-		c.Session.Set("uid", u.ID)
-		c.Session.Set("uname", u.Name)
+		_ = c.Session.Set("uid", u.ID)
+		_ = c.Session.Set("uname", u.Name)
 	}
 
 	log.Info("First-time run install finished!")

+ 3 - 3
internal/route/repo/http.go

@@ -314,9 +314,9 @@ func getInfoRefs(h serviceHandler) {
 	refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
 	h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
 	h.w.WriteHeader(http.StatusOK)
-	h.w.Write(packetWrite("# service=git-" + service + "\n"))
-	h.w.Write([]byte("0000"))
-	h.w.Write(refs)
+	_, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
+	_, _ = h.w.Write([]byte("0000"))
+	_, _ = h.w.Write(refs)
 }
 
 func getTextFile(h serviceHandler) {

+ 12 - 12
internal/route/user/auth.go

@@ -64,8 +64,8 @@ func AutoLogin(c *context.Context) (bool, error) {
 	}
 
 	isSucceed = true
-	c.Session.Set("uid", u.ID)
-	c.Session.Set("uname", u.Name)
+	_ = c.Session.Set("uid", u.ID)
+	_ = c.Session.Set("uname", u.Name)
 	c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
 	if conf.Security.EnableLoginStatusCookie {
 		c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath)
@@ -124,10 +124,10 @@ func afterLogin(c *context.Context, u *db.User, remember bool) {
 		c.SetSuperSecureCookie(u.Rands+u.Passwd, conf.Security.CookieRememberName, u.Name, days, conf.Server.Subpath, "", conf.Security.CookieSecure, true)
 	}
 
-	c.Session.Set("uid", u.ID)
-	c.Session.Set("uname", u.Name)
-	c.Session.Delete("twoFactorRemember")
-	c.Session.Delete("twoFactorUserID")
+	_ = c.Session.Set("uid", u.ID)
+	_ = c.Session.Set("uname", u.Name)
+	_ = c.Session.Delete("twoFactorRemember")
+	_ = c.Session.Delete("twoFactorUserID")
 
 	// Clear whatever CSRF has right now, force to generate a new one
 	c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
@@ -187,8 +187,8 @@ func LoginPost(c *context.Context, f form.SignIn) {
 		return
 	}
 
-	c.Session.Set("twoFactorRemember", f.Remember)
-	c.Session.Set("twoFactorUserID", u.ID)
+	_ = c.Session.Set("twoFactorRemember", f.Remember)
+	_ = c.Session.Set("twoFactorUserID", u.ID)
 	c.RedirectSubpath("/user/login/two_factor")
 }
 
@@ -281,8 +281,8 @@ func LoginTwoFactorRecoveryCodePost(c *context.Context) {
 }
 
 func SignOut(c *context.Context) {
-	c.Session.Flush()
-	c.Session.Destory(c.Context)
+	_ = c.Session.Flush()
+	_ = c.Session.Destory(c.Context)
 	c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath)
 	c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath)
 	c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
@@ -426,8 +426,8 @@ func Activate(c *context.Context) {
 
 		log.Trace("User activated: %s", user.Name)
 
-		c.Session.Set("uid", user.ID)
-		c.Session.Set("uname", user.Name)
+		_ = c.Session.Set("uid", user.ID)
+		_ = c.Session.Set("uname", user.Name)
 		c.RedirectSubpath("/")
 		return
 	}

+ 7 - 5
internal/route/user/setting.go

@@ -127,7 +127,9 @@ func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *db.User) er
 		if err != nil {
 			return fmt.Errorf("open avatar reader: %v", err)
 		}
-		defer r.Close()
+		defer func() {
+			_ = r.Close()
+		}()
 
 		data, err := ioutil.ReadAll(r)
 		if err != nil {
@@ -429,8 +431,8 @@ func SettingsTwoFactorEnable(c *context.Context) {
 	}
 	c.Data["QRCode"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()))
 
-	c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"])
-	c.Session.Set("twoFactorURL", key.String())
+	_ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"])
+	_ = c.Session.Set("twoFactorURL", key.String())
 	c.Success(SETTINGS_TWO_FACTOR_ENABLE)
 }
 
@@ -453,8 +455,8 @@ func SettingsTwoFactorEnablePost(c *context.Context) {
 		return
 	}
 
-	c.Session.Delete("twoFactorSecret")
-	c.Session.Delete("twoFactorURL")
+	_ = c.Session.Delete("twoFactorSecret")
+	_ = c.Session.Delete("twoFactorURL")
 	c.Flash.Success(c.Tr("settings.two_factor_enable_success"))
 	c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes")
 }

+ 14 - 8
internal/ssh/ssh.go

@@ -33,7 +33,7 @@ func cleanCommand(cmd string) string {
 func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
 	for newChan := range chans {
 		if newChan.ChannelType() != "session" {
-			newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
+			_ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
 			continue
 		}
 
@@ -44,7 +44,9 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
 		}
 
 		go func(in <-chan *ssh.Request) {
-			defer ch.Close()
+			defer func() {
+				_ = ch.Close()
+			}()
 			for req := range in {
 				payload := cleanCommand(string(req.Payload))
 				switch req.Type {
@@ -91,17 +93,19 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
 						return
 					}
 
-					req.Reply(true, nil)
-					go io.Copy(input, ch)
-					io.Copy(ch, stdout)
-					io.Copy(ch.Stderr(), stderr)
+					_ = req.Reply(true, nil)
+					go func() {
+						_, _ = io.Copy(input, ch)
+					}()
+					_, _ = io.Copy(ch, stdout)
+					_, _ = io.Copy(ch.Stderr(), stderr)
 
 					if err = cmd.Wait(); err != nil {
 						log.Error("SSH: Wait: %v", err)
 						return
 					}
 
-					ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
+					_, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
 					return
 				default:
 				}
@@ -165,7 +169,9 @@ func Listen(host string, port int, ciphers []string) {
 
 	keyPath := filepath.Join(conf.Server.AppDataPath, "ssh", "gogs.rsa")
 	if !com.IsExist(keyPath) {
-		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
+		if err := os.MkdirAll(filepath.Dir(keyPath), os.ModePerm); err != nil {
+			panic(err)
+		}
 		_, stderr, err := com.ExecCmd(conf.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
 		if err != nil {
 			panic(fmt.Sprintf("Failed to generate private key: %v - %s", err, stderr))

+ 3 - 3
internal/tool/tool.go

@@ -30,7 +30,7 @@ import (
 // MD5Bytes encodes string to MD5 bytes.
 func MD5Bytes(str string) []byte {
 	m := md5.New()
-	m.Write([]byte(str))
+	_, _ = m.Write([]byte(str))
 	return m.Sum(nil)
 }
 
@@ -42,7 +42,7 @@ func MD5(str string) string {
 // SHA1 encodes string to SHA1 hex value.
 func SHA1(str string) string {
 	h := sha1.New()
-	h.Write([]byte(str))
+	_, _ = h.Write([]byte(str))
 	return hex.EncodeToString(h.Sum(nil))
 }
 
@@ -182,7 +182,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
 func HashEmail(email string) string {
 	email = strings.ToLower(strings.TrimSpace(email))
 	h := md5.New()
-	h.Write([]byte(email))
+	_, _ = h.Write([]byte(email))
 	return hex.EncodeToString(h.Sum(nil))
 }