github.com/searKing/golang/go@v1.2.117/net/mux/matcher_http1.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mux 6 7 import ( 8 "io" 9 "net/http" 10 "strings" 11 12 http_ "github.com/searKing/golang/go/net/http" 13 httputil "github.com/searKing/golang/go/net/mux/internal/http" 14 ) 15 16 // HTTP1Fast only matches the methods in the HTTP request. 17 // 18 // This matcher is very optimistic: if it returns true, it does not mean that 19 // the request is a valid HTTP response. If you want a correct but slower HTTP1 20 // matcher, use HTTP1 instead. 21 func HTTP1Fast(extMethods ...string) MatcherFunc { 22 return AnyPrefixMatcher(append(http_.Methods, extMethods...)...) 23 } 24 25 // HTTP1 parses the first line or upto 4096 bytes of the request to see if 26 // the conection contains an HTTP request. 27 func HTTP1() MatcherFunc { 28 return func(_ io.Writer, r io.Reader) bool { 29 req := httputil.ReadRequestLine(r) 30 if req == nil { 31 return false 32 } 33 return req.ProtoMajor == 1 34 } 35 } 36 37 // HTTP1Header returns true if all headers are expected 38 func HTTP1Header(match func(actual, expect http.Header) bool, expect http.Header) MatcherFunc { 39 return func(_ io.Writer, r io.Reader) bool { 40 return httputil.MatchHTTPHeader(r, func(parsedHeader http.Header) bool { 41 return match(parsedHeader, expect) 42 }) 43 } 44 } 45 46 // helper functions 47 48 // HTTP1HeaderValue returns true if all headers are expected, shorthand for HTTP1Header 49 // strings.Match for all value in expects 50 func HTTP1HeaderValue(match func(actualVal, expectVal string) bool, expect http.Header) MatcherFunc { 51 return HTTP1Header(func(actual, expect http.Header) bool { 52 for name := range expect { 53 if match(actual.Get(name), expect.Get(name)) { 54 return false 55 } 56 } 57 return true 58 }, expect) 59 } 60 61 // HTTP1HeaderEqual returns a matcher matching the header fields of the first 62 // request of an HTTP 1 connection. 63 // strings.Equal for all value in expects 64 func HTTP1HeaderEqual(header http.Header) MatcherFunc { 65 return HTTP1HeaderValue(func(actual string, expect string) bool { 66 return actual == expect 67 }, header) 68 } 69 70 // HTTP1HeaderPrefix returns a matcher matching the header fields of the 71 // first request of an HTTP 1 connection. If the header with key name has a 72 // value prefixed with valuePrefix, this will match. 73 // strings.HasPrefix for all value in expects 74 func HTTP1HeaderPrefix(header http.Header) MatcherFunc { 75 return HTTP1HeaderValue(strings.HasPrefix, header) 76 }