From eabc1beff4a738a1a66f2f182ec7b23ac9f13949 Mon Sep 17 00:00:00 2001 From: huhu415 Date: Mon, 11 Nov 2024 22:30:36 +0800 Subject: [PATCH] enhance: performance --- handle/tools.go | 48 ++++++++++++++++++++++++++++++-------- handle/tools_test.go | 55 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 10 deletions(-) create mode 100644 handle/tools_test.go diff --git a/handle/tools.go b/handle/tools.go index 485c217..ca372c3 100644 --- a/handle/tools.go +++ b/handle/tools.go @@ -11,22 +11,50 @@ import ( "github.com/v2fly/v2ray-core/v5/transport/internet/tcp" ) -var anyMethods = []string{ - http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, - http.MethodHead, http.MethodOptions, http.MethodDelete, - http.MethodTrace, "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", - http.MethodConnect, +var anyMethodSet = map[string]struct{}{ + http.MethodGet: {}, + http.MethodPost: {}, + http.MethodPut: {}, + http.MethodPatch: {}, + http.MethodHead: {}, + http.MethodOptions: {}, + http.MethodDelete: {}, + http.MethodTrace: {}, + http.MethodConnect: {}, + "PROPFIND": {}, + "PROPPATCH": {}, + "MKCOL": {}, + "COPY": {}, + "MOVE": {}, + "LOCK": {}, + "UNLOCK": {}, + "LINK": {}, + "UNLINK": {}, + "PURGE": {}, + "VIEW": {}, + "REPORT": {}, + "SEARCH": {}, + "CHECKOUT": {}, + "CHECKIN": {}, + "MERGE": {}, + "SUBSCRIBE": {}, + "UNSUBSCRIBE": {}, + "NOTIFY": {}, } func isHTTP(peek []byte) bool { tempPeekString := strings.ToUpper(string(peek)) logrus.Debug(tempPeekString) - for _, m := range anyMethods { - if strings.HasPrefix(tempPeekString, m) { - return true - } + + first, _, ok := strings.Cut(tempPeekString, " ") + if !ok { + return false + } + + if _, ok := anyMethodSet[first]; !ok { + return false } - return false + return true } func isEnglishLetter(b byte) bool { diff --git a/handle/tools_test.go b/handle/tools_test.go new file mode 100644 index 0000000..ec686c0 --- /dev/null +++ b/handle/tools_test.go @@ -0,0 +1,55 @@ +package handle + +import "testing" + +func Test_isHTTP(t *testing.T) { + tests := []struct { + peek []byte + want bool + }{ + { + peek: []byte("GET /path "), // 10 bytes + want: true, + }, + { + peek: []byte("POST /path "), // 10 bytes + want: true, + }, + { + peek: []byte("put /path "), // 10 bytes + want: true, + }, + { + peek: []byte(" "), // 10 spaces + want: false, + }, + { + peek: []byte("INVALID /p "), // 10 bytes + want: false, + }, + { + peek: []byte("GET "), // 10 bytes + want: true, + }, + { + peek: []byte("GET /p?k=v"), // 10 bytes + want: true, + }, + { + peek: []byte("DELETE /pa"), // 10 bytes + want: true, + }, + { + peek: []byte("PROPPATCH 123123"), // 10 bytes + want: true, + }, + } + + for _, tt := range tests { + t.Run("isHttp", func(t *testing.T) { + if got := isHTTP(tt.peek); got != tt.want { + t.Errorf("isHTTP() = %v, want %v", got, tt.want) + } + }) + } +}