2023-12-08 20:37:20 +00:00
|
|
|
package httputil
|
2023-07-20 16:26:40 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"regexp"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2023-07-26 16:46:49 +00:00
|
|
|
|
2024-02-15 05:46:47 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/v5/api"
|
2023-07-20 16:26:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// match a number with optional decimals
|
|
|
|
var priorityRegex = regexp.MustCompile(`q=(\d+(?:\.\d+)?)`)
|
|
|
|
|
2024-01-18 17:41:31 +00:00
|
|
|
// RespondWithSsz takes a http request and checks to see if it should be requesting a ssz response.
|
|
|
|
func RespondWithSsz(req *http.Request) bool {
|
2023-07-20 16:26:40 +00:00
|
|
|
accept := req.Header.Values("Accept")
|
|
|
|
if len(accept) == 0 {
|
2023-09-27 12:51:37 +00:00
|
|
|
return false
|
2023-07-20 16:26:40 +00:00
|
|
|
}
|
|
|
|
types := strings.Split(accept[0], ",")
|
|
|
|
currentType, currentPriority := "", 0.0
|
|
|
|
for _, t := range types {
|
|
|
|
values := strings.Split(t, ";")
|
|
|
|
name := values[0]
|
2023-07-26 16:46:49 +00:00
|
|
|
if name != api.JsonMediaType && name != api.OctetStreamMediaType {
|
2023-07-20 16:26:40 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
// no params specified
|
|
|
|
if len(values) == 1 {
|
|
|
|
priority := 1.0
|
|
|
|
if priority > currentPriority {
|
|
|
|
currentType, currentPriority = name, priority
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
params := values[1]
|
|
|
|
|
|
|
|
match := priorityRegex.FindAllStringSubmatch(params, 1)
|
|
|
|
if len(match) != 1 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
priority, err := strconv.ParseFloat(match[0][1], 32)
|
|
|
|
if err != nil {
|
2023-09-27 12:51:37 +00:00
|
|
|
return false
|
2023-07-20 16:26:40 +00:00
|
|
|
}
|
|
|
|
if priority > currentPriority {
|
|
|
|
currentType, currentPriority = name, priority
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-27 12:51:37 +00:00
|
|
|
return currentType == api.OctetStreamMediaType
|
2023-07-20 16:26:40 +00:00
|
|
|
}
|
2024-01-18 17:41:31 +00:00
|
|
|
|
|
|
|
// IsRequestSsz checks if the request object should be interpreted as ssz
|
|
|
|
func IsRequestSsz(req *http.Request) bool {
|
|
|
|
return req.Header.Get("Content-Type") == api.OctetStreamMediaType
|
|
|
|
}
|