-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-utils.go
42 lines (37 loc) · 1.18 KB
/
server-utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package utils
import (
"errors"
"github.com/charmbracelet/log"
"net/http"
"strings"
)
// logHttpServerError is the internal function powering the logging in
// RunBackgroundHttp and RunBackgroundHttps.
func logHttpServerError(logger *log.Logger, err error) {
if err != nil {
if errors.Is(err, http.ErrServerClosed) {
logger.Info("The http server shutdown successfully")
} else {
logger.Info("Error trying to host the http server", "err", err.Error())
}
}
}
// RunBackgroundHttp runs a http server and logs when the server closes or
// errors.
func RunBackgroundHttp(logger *log.Logger, s *http.Server) {
logHttpServerError(logger, s.ListenAndServe())
}
// RunBackgroundHttps runs a http server with TLS encryption and logs when the
// server closes or errors.
func RunBackgroundHttps(logger *log.Logger, s *http.Server) {
logHttpServerError(logger, s.ListenAndServeTLS("", ""))
}
// GetBearer returns the bearer from the Authorization header or an empty string
// if the authorization is empty or doesn't start with Bearer.
func GetBearer(req *http.Request) string {
a := req.Header.Get("Authorization")
if t, ok := strings.CutPrefix(a, "Bearer "); ok {
return t
}
return ""
}