54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
"net/url"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
var cacheETag = strconv.FormatInt(time.Now().Unix(), 16)
|
||
|
|
||
|
func RequestKiller(rw http.ResponseWriter) {
|
||
|
if hi, ok := rw.(http.Hijacker); ok {
|
||
|
conn, _, err := hi.Hijack()
|
||
|
if err == nil {
|
||
|
_ = conn.Close()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func GetBearerToken(req *http.Request) string {
|
||
|
auth := req.Header.Get("Authorization")
|
||
|
if strings.HasPrefix(strings.ToLower(auth), "bearer ") {
|
||
|
return auth[len("bearer "):]
|
||
|
}
|
||
|
return ""
|
||
|
}
|
||
|
|
||
|
func CachedPage(cb func(rw http.ResponseWriter, req *http.Request)) func(rw http.ResponseWriter, req *http.Request) {
|
||
|
return func(rw http.ResponseWriter, req *http.Request) {
|
||
|
if req.Header.Get("If-None-Match") == req.RequestURI+"."+cacheETag {
|
||
|
rw.WriteHeader(http.StatusNotModified)
|
||
|
return
|
||
|
}
|
||
|
rw.Header().Set("Etag", req.RequestURI+"."+cacheETag)
|
||
|
cb(rw, req)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// CloneURL is copied from https://github.com/golang/go/blob/go1.19/src/net/http/clone.go#L22
|
||
|
func CloneURL(u *url.URL) *url.URL {
|
||
|
if u == nil {
|
||
|
return nil
|
||
|
}
|
||
|
u2 := new(url.URL)
|
||
|
*u2 = *u
|
||
|
if u.User != nil {
|
||
|
u2.User = new(url.Userinfo)
|
||
|
*u2.User = *u.User
|
||
|
}
|
||
|
return u2
|
||
|
}
|