yanic/webserver/webserver.go

37 lines
921 B
Go
Raw Normal View History

2017-01-29 20:06:56 +01:00
package webserver
import (
"net/http"
2024-07-05 02:08:54 +02:00
"github.com/FreifunkBremen/yanic/runtime"
2017-01-29 20:06:56 +01:00
"github.com/NYTimes/gziphandler"
2019-01-17 13:26:16 +01:00
"github.com/bdlm/log"
2024-07-05 02:08:54 +02:00
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
2017-01-29 20:06:56 +01:00
)
// New creates a new webserver and starts it
2024-07-05 02:08:54 +02:00
func New(config Config, nodes *runtime.Nodes) *http.Server {
mux := http.NewServeMux()
if config.Prometheus != nil && config.Prometheus.Enable {
config.Prometheus.Init(nodes)
prometheus.MustRegister(config.Prometheus)
mux.Handle("/metrics", promhttp.Handler())
}
if config.Webroot != "" {
mux.Handle("/", gziphandler.GzipHandler(http.FileServer(http.Dir(config.Webroot))))
}
return &http.Server{
2024-07-05 02:08:54 +02:00
Addr: config.Bind,
Handler: mux,
2017-01-29 20:06:56 +01:00
}
}
2017-01-29 20:06:56 +01:00
func Start(srv *http.Server) {
// service connections
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
2019-01-17 13:26:16 +01:00
log.Panicf("webserver crashed: %s", err)
}
2017-01-29 20:06:56 +01:00
}