From 0c064b1b79bc5fe0558fb5ba1a185cfc27a77f75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=B4=9C=C9=B4=E1=B4=8B=C9=B4=E1=B4=A1=E1=B4=8F=C9=B4?= Date: Mon, 24 Feb 2020 21:13:56 +0800 Subject: [PATCH] cmd/web: fix error when Unix socket not exists --- internal/cmd/web.go | 12 ++++++++---- internal/osutil/osutil.go | 6 ++++++ internal/osutil/osutil_test.go | 23 +++++++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/internal/cmd/web.go b/internal/cmd/web.go index 30501bde2..e78eefcc8 100644 --- a/internal/cmd/web.go +++ b/internal/cmd/web.go @@ -35,6 +35,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/form" + "gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/route" "gogs.io/gogs/internal/route/admin" apiv1 "gogs.io/gogs/internal/route/api/v1" @@ -690,10 +691,11 @@ func runWeb(c *cli.Context) error { var listenAddr string if conf.Server.Protocol == "unix" { listenAddr = conf.Server.HTTPAddr + log.Info("Listen on %v://%s", conf.Server.Protocol, listenAddr) } else { listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort) + log.Info("Listen on %v://%s%s", conf.Server.Protocol, listenAddr, conf.Server.Subpath) } - log.Info("Listen on %v://%s%s", conf.Server.Protocol, listenAddr, conf.Server.Subpath) switch conf.Server.Protocol { case "http": @@ -732,9 +734,11 @@ func runWeb(c *cli.Context) error { err = fcgi.Serve(nil, m) case "unix": - err = os.Remove(listenAddr) - if err != nil { - log.Fatal("Failed to remove existing Unix domain socket: %v", err) + if osutil.IsExist(listenAddr) { + err = os.Remove(listenAddr) + if err != nil { + log.Fatal("Failed to remove existing Unix domain socket: %v", err) + } } var listener *net.UnixListener diff --git a/internal/osutil/osutil.go b/internal/osutil/osutil.go index 656f2e2a3..827988a0b 100644 --- a/internal/osutil/osutil.go +++ b/internal/osutil/osutil.go @@ -17,6 +17,12 @@ func IsFile(path string) bool { return !f.IsDir() } +// IsExist returns true if a file or directory exists. +func IsExist(path string) bool { + _, err := os.Stat(path) + return err == nil || os.IsExist(err) +} + // CurrentUsername returns the current system user via environment variables. func CurrentUsername() string { curUserName := os.Getenv("USER") diff --git a/internal/osutil/osutil_test.go b/internal/osutil/osutil_test.go index adaebebf0..4c9a2ad73 100644 --- a/internal/osutil/osutil_test.go +++ b/internal/osutil/osutil_test.go @@ -32,3 +32,26 @@ func TestIsFile(t *testing.T) { }) } } + +func TestIsExist(t *testing.T) { + tests := []struct { + path string + expVal bool + }{ + { + path: "osutil.go", + expVal: true, + }, { + path: "../osutil", + expVal: true, + }, { + path: "not_found", + expVal: false, + }, + } + for _, test := range tests { + t.Run("", func(t *testing.T) { + assert.Equal(t, test.expVal, IsExist(test.path)) + }) + } +}