1
0
mirror of https://github.com/mxpv/podsync.git synced 2024-05-11 05:55:04 +00:00

Implement initial static file server

This commit is contained in:
Maksym Pavlenko
2019-10-29 13:30:51 -07:00
parent acee1d9cfc
commit cce3728828
3 changed files with 61 additions and 25 deletions

View File

@@ -2,16 +2,16 @@ package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"github.com/mxpv/podsync/pkg/config"
"github.com/mxpv/podsync/pkg/web"
)
type Opts struct {
@@ -28,6 +28,8 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
group, ctx := errgroup.WithContext(ctx)
// Parse args
opts := Opts{}
_, err := flags.Parse(&opts)
@@ -46,32 +48,35 @@ func main() {
log.WithError(err).Fatal("failed to load configuration file")
}
// Create web server
port := cfg.Server.Port
if port == 0 {
port = 8080
}
srv := web.New(cfg)
srv := http.Server{
Addr: fmt.Sprintf(":%d", port),
}
log.Debugf("using address %s", srv.Addr)
// Run listener
go func() {
group.Go(func() error {
log.Infof("running listener at %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
log.WithError(err).Error("failed to listen")
return srv.ListenAndServe()
})
group.Go(func() error {
// Shutdown web server
defer func() {
log.Info("shutting down web server")
if err := srv.Shutdown(ctx); err != nil {
log.WithError(err).Error("server shutdown failed")
}
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-stop:
cancel()
return nil
}
}
}()
})
<-stop
log.Info("shutting down")
if err := srv.Shutdown(ctx); err != nil {
log.WithError(err).Error("server shutdown failed")
if err := group.Wait(); err != nil && err != context.Canceled {
log.WithError(err).Error("wait error")
}
log.Info("gracefully stopped")

2
go.mod
View File

@@ -17,7 +17,7 @@ require (
github.com/vmihailenco/msgpack v4.0.4+incompatible
golang.org/x/net v0.0.0-20190311183353-d8887717615a
golang.org/x/oauth2 v0.0.0-20180620175406-ef147856a6dd
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 // indirect
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4
golang.org/x/sys v0.0.0-20190311152110-c8c8c57fd1e1 // indirect
google.golang.org/api v0.0.0-20180718221112-efcb5f25ac56
google.golang.org/appengine v1.1.0 // indirect

31
pkg/web/server.go Normal file
View File

@@ -0,0 +1,31 @@
package web
import (
"fmt"
"net/http"
log "github.com/sirupsen/logrus"
"github.com/mxpv/podsync/pkg/config"
)
type Server struct {
http.Server
}
func New(cfg *config.Config) *Server {
port := cfg.Server.Port
if port == 0 {
port = 8080
}
srv := Server{}
srv.Addr = fmt.Sprintf(":%d", port)
log.Debugf("using address: %s", srv.Addr)
fs := http.FileServer(http.Dir(cfg.Server.DataDir))
http.Handle("/", fs)
return &srv
}