2023-04-21 03:21:46 +01:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-04-24 15:36:21 +01:00
|
|
|
// 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 {
|
|
|
|
if err == http.ErrServerClosed {
|
|
|
|
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())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 15:36:21 +01:00
|
|
|
// 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())
|
|
|
|
}
|
|
|
|
|
2023-04-24 15:36:21 +01:00
|
|
|
// 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 ""
|
|
|
|
}
|