github.com/searKing/golang/go@v1.2.117/net/mux/matcher_http2.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 "io/ioutil" 10 "strings" 11 12 "golang.org/x/net/http2/hpack" 13 14 http2_ "github.com/searKing/golang/go/net/mux/internal/http2" 15 ) 16 17 // HTTP2 parses the frame header of the first frame to detect whether the 18 // connection is an HTTP2 connection. 19 func HTTP2() MatcherFunc { 20 return func(_ io.Writer, r io.Reader) bool { 21 return http2_.HasClientPreface(r) 22 } 23 } 24 25 // HTTP2HeaderField returns a matcher matching the header fields of the first 26 // headers frame. 27 // writes the settings to the server if sendSetting is true. 28 // Prefer HTTP2HeaderField over this one, if the client does not block on receiving a SETTING frame. 29 func HTTP2HeaderField(sendSetting bool, 30 match func(actual, expect map[string]hpack.HeaderField) bool, 31 expects ...hpack.HeaderField) MatcherFunc { 32 return func(w io.Writer, r io.Reader) bool { 33 if !sendSetting { 34 w = ioutil.Discard 35 } 36 return http2_.MatchHTTP2Header(w, r, nil, func(parsedHeader map[string]hpack.HeaderField) bool { 37 var expectMap = map[string]hpack.HeaderField{} 38 for _, expect := range expects { 39 expectMap[expect.Name] = expect 40 } 41 return match(parsedHeader, expectMap) 42 }) 43 } 44 } 45 46 // helper functions 47 func HTTP2HeaderFieldValue(sendSetting bool, match func(actualVal, expectVal string) bool, expects ...hpack.HeaderField) MatcherFunc { 48 return HTTP2HeaderField(sendSetting, func(actualHeaderByName, expectHeaderByName map[string]hpack.HeaderField) bool { 49 for name := range expectHeaderByName { 50 if match(actualHeaderByName[name].Value, expectHeaderByName[name].Value) { 51 return false 52 } 53 } 54 return true 55 }, expects...) 56 } 57 58 // HTTP2HeaderFieldEqual returns a matcher matching the header fields. 59 func HTTP2HeaderFieldEqual(sendSetting bool, headers ...hpack.HeaderField) MatcherFunc { 60 return HTTP2HeaderFieldValue(sendSetting, func(actual string, expect string) bool { 61 return actual == expect 62 }, headers...) 63 } 64 65 // HTTP2HeaderFieldPrefix returns a matcher matching the header fields. 66 // If the header with key name has a 67 // value prefixed with valuePrefix, this will match. 68 func HTTP2HeaderFieldPrefix(sendSetting bool, headers ...hpack.HeaderField) MatcherFunc { 69 return HTTP2HeaderFieldValue(sendSetting, strings.HasPrefix, headers...) 70 }