add MethodFrom

This commit is contained in:
Patricio Whittingslow
2026-07-26 11:13:29 -03:00
parent 10932ebf34
commit b79e58b812
+12 -4
View File
@@ -113,7 +113,7 @@ func (sm *MuxSlice) Handle(optMethodAndPath string, handler HandlerFunc) {
method := MethUndefined method := MethUndefined
methodOrURL, url, methodFound := strings.Cut(optMethodAndPath, " ") methodOrURL, url, methodFound := strings.Cut(optMethodAndPath, " ")
if methodFound { if methodFound {
method = MethodFromBytes([]byte(methodOrURL)) method = MethodFrom(methodOrURL)
} else { } else {
url = methodOrURL url = methodOrURL
} }
@@ -141,14 +141,14 @@ const (
MethUnknown // unknown MethUnknown // unknown
) )
// MethodFromBytes returns the [Method] matching meth, [MethUndefined] if meth is // MethodFrom returns the [Method] matching meth, [MethUndefined] if meth is
// empty and [MethUnknown] if it names a method this package does not know. // empty and [MethUnknown] if it names a method this package does not know.
// Comparison is case sensitive: methods are uppercase, RFC 9110 9.1. // Comparison is case sensitive: methods are uppercase, RFC 9110 9.1.
func MethodFromBytes(meth []byte) (res Method) { func MethodFrom(meth string) (res Method) {
if len(meth) == 0 { if len(meth) == 0 {
return MethUndefined return MethUndefined
} }
switch unsafe.String(&meth[0], len(meth)) { switch meth {
case "GET": case "GET":
res = MethGet res = MethGet
case "HEAD": case "HEAD":
@@ -173,6 +173,14 @@ func MethodFromBytes(meth []byte) (res Method) {
return res return res
} }
// MethodFromBytes is a [MethodFrom] wrapper with bytes argument instead of string.
func MethodFromBytes(meth []byte) (res Method) {
if len(meth) == 0 {
return MethUndefined
}
return MethodFrom(b2s(meth))
}
// b2s converts byte slice to a string without memory allocation. // b2s converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ . // See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
func b2s(b []byte) string { func b2s(b []byte) string {