violet/utils/server-utils.go

43 lines
1.2 KiB
Go
Raw Permalink Normal View History

2023-04-21 03:21:46 +01:00
package utils
import (
2023-08-30 13:24:39 +01:00
"errors"
2023-04-21 03:21:46 +01:00
"log"
"net/http"
"strings"
)
// logHttpServerError is the internal function powering the logging in
// RunBackgroundHttp and RunBackgroundHttps.
2023-04-21 03:21:46 +01:00
func logHttpServerError(prefix string, err error) {
if err != nil {
2023-08-30 13:24:39 +01:00
if errors.Is(err, http.ErrServerClosed) {
2023-04-21 03:21:46 +01:00
log.Printf("[%s] The http server shutdown successfully\n", prefix)
} else {
log.Printf("[%s] Error trying to host the http server: %s\n", prefix, err.Error())
}
}
}
// RunBackgroundHttp runs a http server and logs when the server closes or
// errors.
2023-04-21 03:21:46 +01:00
func RunBackgroundHttp(prefix string, s *http.Server) {
logHttpServerError(prefix, s.ListenAndServe())
}
// RunBackgroundHttps runs a http server with TLS encryption and logs when the
// server closes or errors.
2023-04-21 03:21:46 +01:00
func RunBackgroundHttps(prefix string, s *http.Server) {
logHttpServerError(prefix, s.ListenAndServeTLS("", ""))
}
2023-04-24 01:35:23 +01:00
// GetBearer returns the bearer from the Authorization header or an empty string
// if the authorization is empty or doesn't start with Bearer.
2023-04-21 03:21:46 +01:00
func GetBearer(req *http.Request) string {
a := req.Header.Get("Authorization")
if t, ok := strings.CutPrefix(a, "Bearer "); ok {
return t
}
return ""
}