refactor: add more go linters (#970)

This commit is contained in:
Oleg Lobanov
2020-06-01 01:12:36 +02:00
committed by GitHub
parent 54d92a2708
commit 700f32718e
56 changed files with 436 additions and 221 deletions

View File

@@ -10,10 +10,15 @@ import (
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/users"
)
const (
TokenExpirationTime = time.Hour * 2
)
type userInfo struct {
ID uint `json:"id"`
Locale string `json:"locale"`
@@ -161,7 +166,7 @@ var renewHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data
return printToken(w, r, d, d.user)
})
func printToken(w http.ResponseWriter, r *http.Request, d *data, user *users.User) (int, error) {
func printToken(w http.ResponseWriter, _ *http.Request, d *data, user *users.User) (int, error) {
claims := &authToken{
User: userInfo{
ID: user.ID,
@@ -173,7 +178,7 @@ func printToken(w http.ResponseWriter, r *http.Request, d *data, user *users.Use
},
StandardClaims: jwt.StandardClaims{
IssuedAt: time.Now().Unix(),
ExpiresAt: time.Now().Add(time.Hour * 2).Unix(),
ExpiresAt: time.Now().Add(TokenExpirationTime).Unix(),
Issuer: "File Browser",
},
}
@@ -185,6 +190,8 @@ func printToken(w http.ResponseWriter, r *http.Request, d *data, user *users.Use
}
w.Header().Set("Content-Type", "cty")
w.Write([]byte(signed))
if _, err := w.Write([]byte(signed)); err != nil {
return http.StatusInternalServerError, err
}
return 0, nil
}

View File

@@ -9,8 +9,13 @@ import (
"strings"
"time"
"github.com/filebrowser/filebrowser/v2/runner"
"github.com/gorilla/websocket"
"github.com/filebrowser/filebrowser/v2/runner"
)
const (
WSWriteDeadline = 10 * time.Second
)
var upgrader = websocket.Upgrader{
@@ -22,12 +27,14 @@ var (
cmdNotAllowed = []byte("Command not allowed.")
)
func wsErr(ws *websocket.Conn, r *http.Request, status int, err error) {
func wsErr(ws *websocket.Conn, r *http.Request, status int, err error) { //nolint:unparam
txt := http.StatusText(status)
if err != nil || status >= 400 {
log.Printf("%s: %v %s %v", r.URL.Path, status, r.RemoteAddr, err)
}
ws.WriteControl(websocket.CloseInternalServerErr, []byte(txt), time.Now().Add(10*time.Second))
if err := ws.WriteControl(websocket.CloseInternalServerErr, []byte(txt), time.Now().Add(WSWriteDeadline)); err != nil { //nolint:shadow
log.Print(err)
}
}
var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
@@ -40,7 +47,7 @@ var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *d
var raw string
for {
_, msg, err := conn.ReadMessage()
_, msg, err := conn.ReadMessage() //nolint:shadow
if err != nil {
wsErr(conn, r, http.StatusInternalServerError, err)
return 0, nil
@@ -53,8 +60,7 @@ var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *d
}
if !d.user.CanExecute(strings.Split(raw, " ")[0]) {
err := conn.WriteMessage(websocket.TextMessage, cmdNotAllowed)
if err != nil {
if err := conn.WriteMessage(websocket.TextMessage, cmdNotAllowed); err != nil { //nolint:shadow
wsErr(conn, r, http.StatusInternalServerError, err)
}
@@ -63,15 +69,13 @@ var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *d
command, err := runner.ParseCommand(d.settings, raw)
if err != nil {
err := conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
if err != nil {
if err := conn.WriteMessage(websocket.TextMessage, []byte(err.Error())); err != nil { //nolint:shadow
wsErr(conn, r, http.StatusInternalServerError, err)
}
return 0, nil
}
cmd := exec.Command(command[0], command[1:]...)
cmd := exec.Command(command[0], command[1:]...) //nolint:gosec
cmd.Dir = d.user.FullPath(r.URL.Path)
stdout, err := cmd.StdoutPipe()
@@ -93,7 +97,9 @@ var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *d
s := bufio.NewScanner(io.MultiReader(stdout, stderr))
for s.Scan() {
conn.WriteMessage(websocket.TextMessage, s.Bytes())
if err := conn.WriteMessage(websocket.TextMessage, s.Bytes()); err != nil {
log.Print(err)
}
}
if err := cmd.Wait(); err != nil {

View File

@@ -41,9 +41,9 @@ func (d *data) Check(path string) bool {
return true
}
func handle(fn handleFunc, prefix string, storage *storage.Storage, server *settings.Server) http.Handler {
func handle(fn handleFunc, prefix string, store *storage.Storage, server *settings.Server) http.Handler {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
settings, err := storage.Settings.Get()
settings, err := store.Settings.Get()
if err != nil {
log.Fatalln("ERROR: couldn't get settings")
return
@@ -51,7 +51,7 @@ func handle(fn handleFunc, prefix string, storage *storage.Storage, server *sett
status, err := fn(w, r, &data{
Runner: &runner.Runner{Settings: settings},
store: storage,
store: store,
settings: settings,
server: server,
})

View File

@@ -3,9 +3,10 @@ package http
import (
"net/http"
"github.com/gorilla/mux"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/gorilla/mux"
)
type modifyRequest struct {
@@ -13,11 +14,11 @@ type modifyRequest struct {
Which []string `json:"which"` // Answer to: which fields?
}
func NewHandler(storage *storage.Storage, server *settings.Server) (http.Handler, error) {
func NewHandler(store *storage.Storage, server *settings.Server) (http.Handler, error) {
server.Clean()
r := mux.NewRouter()
index, static := getStaticHandlers(storage, server)
index, static := getStaticHandlers(store, server)
// NOTE: This fixes the issue where it would redirect if people did not put a
// trailing slash in the end. I hate this decision since this allows some awful
@@ -25,7 +26,7 @@ func NewHandler(storage *storage.Storage, server *settings.Server) (http.Handler
r = r.SkipClean(true)
monkey := func(fn handleFunc, prefix string) http.Handler {
return handle(fn, prefix, storage, server)
return handle(fn, prefix, store, server)
}
r.PathPrefix("/static").Handler(static)

View File

@@ -46,7 +46,7 @@ func ifPathWithName(r *http.Request) string {
pathElements := strings.Split(r.URL.Path, "/")
// prevent maliciously constructed parameters like `/api/public/dl/XZzCDnK2_not_exists_hash_name`
// len(pathElements) will be 1, and golang will panic `runtime error: index out of range`
if len(pathElements) < 2 {
if len(pathElements) < 2 { //nolint: mnd
return r.URL.Path
}
id := pathElements[len(pathElements)-2]

View File

@@ -7,34 +7,37 @@ import (
"path/filepath"
"strings"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/users"
"github.com/hacdias/fileutils"
"github.com/mholt/archiver"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/users"
)
func parseQueryFiles(r *http.Request, f *files.FileInfo, u *users.User) ([]string, error) {
files := []string{}
func parseQueryFiles(r *http.Request, f *files.FileInfo, _ *users.User) ([]string, error) {
var fileSlice []string
names := strings.Split(r.URL.Query().Get("files"), ",")
if len(names) == 0 {
files = append(files, f.Path)
fileSlice = append(fileSlice, f.Path)
} else {
for _, name := range names {
name, err := url.QueryUnescape(strings.Replace(name, "+", "%2B", -1))
name, err := url.QueryUnescape(strings.Replace(name, "+", "%2B", -1)) //nolint:shadow
if err != nil {
return nil, err
}
name = fileutils.SlashClean(name)
files = append(files, filepath.Join(f.Path, name))
fileSlice = append(fileSlice, filepath.Join(f.Path, name))
}
}
return files, nil
return fileSlice, nil
}
//nolint: goconst
func parseQueryAlgorithm(r *http.Request) (string, archiver.Writer, error) {
// TODO: use enum
switch r.URL.Query().Get("algo") {
case "zip", "true", "":
return ".zip", archiver.NewZip(), nil

View File

@@ -74,7 +74,7 @@ var resourcePostPutHandler = withUser(func(w http.ResponseWriter, r *http.Reques
}
defer func() {
io.Copy(ioutil.Discard, r.Body)
_, _ = io.Copy(ioutil.Discard, r.Body)
}()
// For directories, only allow POST for creation.
@@ -119,6 +119,7 @@ var resourcePostPutHandler = withUser(func(w http.ResponseWriter, r *http.Reques
return errToStatus(err), err
})
//nolint: goconst
var resourcePatchHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
src := r.URL.Path
dst := r.URL.Query().Get("destination")
@@ -134,6 +135,7 @@ var resourcePatchHandler = withUser(func(w http.ResponseWriter, r *http.Request,
}
switch action {
// TODO: use enum
case "copy":
if !d.user.Perm.Create {
return http.StatusForbidden, nil

View File

@@ -57,7 +57,9 @@ var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request
var err error
s, err = d.store.Share.GetPermanent(r.URL.Path, d.user.ID)
if err == nil {
w.Write([]byte(path.Join(d.server.BaseURL, "/share/", s.Hash)))
if _, err := w.Write([]byte(path.Join(d.server.BaseURL, "/share/", s.Hash))); err != nil {
return http.StatusInternalServerError, err
}
return 0, nil
}
}

View File

@@ -11,13 +11,14 @@ import (
"text/template"
rice "github.com/GeertJohan/go.rice"
"github.com/filebrowser/filebrowser/v2/auth"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/version"
)
func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *data, box *rice.Box, file, contentType string) (int, error) {
func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, box *rice.Box, file, contentType string) (int, error) {
w.Header().Set("Content-Type", contentType)
auther, err := d.store.Auth.Get(d.settings.AuthMethod)
@@ -41,8 +42,8 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *data, box *
}
if d.settings.Branding.Files != "" {
path := filepath.Join(d.settings.Branding.Files, "custom.css")
_, err := os.Stat(path)
fPath := filepath.Join(d.settings.Branding.Files, "custom.css")
_, err := os.Stat(fPath) //nolint:shadow
if err != nil && !os.IsNotExist(err) {
log.Printf("couldn't load custom styles: %v", err)
@@ -54,7 +55,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *data, box *
}
if d.settings.AuthMethod == auth.MethodJSONAuth {
raw, err := d.store.Auth.Get(d.settings.AuthMethod)
raw, err := d.store.Auth.Get(d.settings.AuthMethod) //nolint:shadow
if err != nil {
return http.StatusInternalServerError, err
}
@@ -84,29 +85,29 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *data, box *
return 0, nil
}
func getStaticHandlers(storage *storage.Storage, server *settings.Server) (http.Handler, http.Handler) {
func getStaticHandlers(store *storage.Storage, server *settings.Server) (index, static http.Handler) {
box := rice.MustFindBox("../frontend/dist")
handler := http.FileServer(box.HTTPBox())
index := handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
index = handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if r.Method != http.MethodGet {
return http.StatusNotFound, nil
}
w.Header().Set("x-xss-protection", "1; mode=block")
return handleWithStaticData(w, r, d, box, "index.html", "text/html; charset=utf-8")
}, "", storage, server)
}, "", store, server)
static := handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
static = handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if r.Method != http.MethodGet {
return http.StatusNotFound, nil
}
if d.settings.Branding.Files != "" {
if strings.HasPrefix(r.URL.Path, "img/") {
path := filepath.Join(d.settings.Branding.Files, r.URL.Path)
if _, err := os.Stat(path); err == nil {
http.ServeFile(w, r, path)
fPath := filepath.Join(d.settings.Branding.Files, r.URL.Path)
if _, err := os.Stat(fPath); err == nil {
http.ServeFile(w, r, fPath)
return 0, nil
}
} else if r.URL.Path == "custom.css" && d.settings.Branding.Files != "" {
@@ -121,7 +122,7 @@ func getStaticHandlers(storage *storage.Storage, server *settings.Server) (http.
}
return handleWithStaticData(w, r, d, box, r.URL.Path, "application/javascript; charset=utf-8")
}, "/static/", storage, server)
}, "/static/", store, server)
return index, static
}

View File

@@ -8,9 +8,10 @@ import (
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/users"
"github.com/gorilla/mux"
)
type modifyUserRequest struct {
@@ -27,7 +28,7 @@ func getUserID(r *http.Request) (uint, error) {
return uint(i), err
}
func getUser(w http.ResponseWriter, r *http.Request) (*modifyUserRequest, error) {
func getUser(_ http.ResponseWriter, r *http.Request) (*modifyUserRequest, error) {
if r.Body == nil {
return nil, errors.ErrEmptyRequest
}

View File

@@ -10,7 +10,7 @@ import (
"github.com/filebrowser/filebrowser/v2/errors"
)
func renderJSON(w http.ResponseWriter, r *http.Request, data interface{}) (int, error) {
func renderJSON(w http.ResponseWriter, _ *http.Request, data interface{}) (int, error) {
marsh, err := json.Marshal(data)
if err != nil {