Skip to content

Commit

Permalink
Apply Gilles' suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
elv-nate committed Jul 11, 2024
1 parent bd5d8e8 commit 5761dcd
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions util/netutil/file_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,35 @@ import (
"context"
"fmt"
"net/http"
"os"
"time"

"github.com/eluv-io/common-go/util/testutil"
"github.com/eluv-io/errors-go"
"github.com/eluv-io/log-go"
)

// NewFileServer creates a lightweight file server.
func NewFileServer(fsRoot string, port int) *FileServer {
// NewFileServer creates a lightweight file server, which is a very thin wrapper around go's
// `http.FileServer`. If port is zero, a free port is used.
//
// This implementation is probably not safe for production use, but good for testing.
func NewFileServer(fsRoot string, port int) (*FileServer, error) {
stat, err := os.Stat(fsRoot)
if err != nil {
return nil, errors.E("NewFileServer", errors.K.IO, err)
}
if !stat.IsDir() {
return nil, errors.E("NewFileServer", errors.K.Invalid,
"reason", "fs_root is not a directory",
"fs_root", fsRoot)
}
if port == 0 {
port, err = testutil.FreePort()
if err != nil {
return nil, errors.E("NewFileServer", errors.K.IO, err)
}
}

h := http.FileServer(http.Dir(fsRoot))
s := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Expand All @@ -22,7 +44,11 @@ func NewFileServer(fsRoot string, port int) *FileServer {
root: fsRoot,
s: s,
log: log.Get("/eluvio/file_server"),
}
}, nil
}

func (fs *FileServer) Port() int {
return fs.port
}

type FileServer struct {
Expand All @@ -37,13 +63,20 @@ func (fs *FileServer) SetLog(l *log.Log) {
fs.log = l
}

func (fs *FileServer) doLog(msg string, args ...interface{}) {
if fs.log == nil {
return
}
fs.log.Info(msg, args...)
}

func (fs *FileServer) Start() {
fs.log.Info("starting file server", "root", fs.root, "port", fs.port)
go func() { fs.log.Info("http server shutdown", fs.s.ListenAndServe()) }()
fs.doLog("starting file server", "root", fs.root, "port", fs.port)
go func() { fs.doLog("file server shutdown", fs.s.ListenAndServe()) }()
}

func (fs *FileServer) Stop() error {
fs.log.Info("shutting down file server", "root", fs.root, "port", fs.port)
fs.doLog("shutting down file server", "root", fs.root, "port", fs.port)
c, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return fs.s.Shutdown(c)
Expand Down

0 comments on commit 5761dcd

Please sign in to comment.