2023-04-21 03:21:46 +01:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2023-08-30 13:24:39 +01:00
|
|
|
"errors"
|
2024-05-13 19:33:33 +01:00
|
|
|
"github.com/charmbracelet/log"
|
2023-04-21 03:21:46 +01:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-04-24 15:36:21 +01:00
|
|
|
// logHttpServerError is the internal function powering the logging in
|
|
|
|
// RunBackgroundHttp and RunBackgroundHttps.
|
2024-05-13 19:33:33 +01:00
|
|
|
func logHttpServerError(logger *log.Logger, err error) {
|
2023-04-21 03:21:46 +01:00
|
|
|
if err != nil {
|
2023-08-30 13:24:39 +01:00
|
|
|
if errors.Is(err, http.ErrServerClosed) {
|
2024-05-13 19:33:33 +01:00
|
|
|
logger.Info("The http server shutdown successfully")
|
2023-04-21 03:21:46 +01:00
|
|
|
} else {
|
2024-05-13 19:33:33 +01:00
|
|
|
logger.Info("Error trying to host the http server", "err", err.Error())
|
2023-04-21 03:21:46 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 15:36:21 +01:00
|
|
|
// RunBackgroundHttp runs a http server and logs when the server closes or
|
|
|
|
// errors.
|
2024-05-13 19:33:33 +01:00
|
|
|
func RunBackgroundHttp(logger *log.Logger, s *http.Server) {
|
|
|
|
logHttpServerError(logger, s.ListenAndServe())
|
2023-04-21 03:21:46 +01:00
|
|
|
}
|
|
|
|
|
2023-04-24 15:36:21 +01:00
|
|
|
// RunBackgroundHttps runs a http server with TLS encryption and logs when the
|
|
|
|
// server closes or errors.
|
2024-05-13 19:33:33 +01:00
|
|
|
func RunBackgroundHttps(logger *log.Logger, s *http.Server) {
|
|
|
|
logHttpServerError(logger, s.ListenAndServeTLS("", ""))
|
2023-04-21 03:21:46 +01:00
|
|
|
}
|
|
|
|
|
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 ""
|
|
|
|
}
|