Improve api listener integration

This commit is contained in:
Daniel 2019-10-04 23:49:13 +02:00
parent d840c85a63
commit adc359c15b
2 changed files with 21 additions and 3 deletions

View file

@ -7,13 +7,17 @@ import (
"github.com/safing/portbase/modules" "github.com/safing/portbase/modules"
) )
var (
module *modules.Module
)
// API Errors // API Errors
var ( var (
ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set") ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set")
) )
func init() { func init() {
modules.Register("api", prep, start, stop, "base", "database", "config") module = modules.Register("api", prep, start, stop, "base", "database", "config")
} }
func prep() error { func prep() error {

View file

@ -1,8 +1,10 @@
package api package api
import ( import (
"context"
"net/http" "net/http"
"sync" "sync"
"time"
"github.com/gorilla/mux" "github.com/gorilla/mux"
@ -56,8 +58,20 @@ func Serve() {
// start serving // start serving
log.Infof("api: starting to listen on %s", server.Addr) log.Infof("api: starting to listen on %s", server.Addr)
// TODO: retry if failed backoffDuration := 10 * time.Second
log.Errorf("api: failed to listen on %s: %s", server.Addr, server.ListenAndServe()) for {
// always returns an error
err := module.RunWorker("http endpoint", func(ctx context.Context) error {
return server.ListenAndServe()
})
// return on shutdown error
if err == http.ErrServerClosed {
return
}
// log error and restart
log.Errorf("api: http endpoint failed: %s - restarting in %s", err, backoffDuration)
time.Sleep(backoffDuration)
}
} }
// GetMuxVars wraps github.com/gorilla/mux.Vars in order to mitigate context key issues in multi-repo projects. // GetMuxVars wraps github.com/gorilla/mux.Vars in order to mitigate context key issues in multi-repo projects.