From 0ed3c5a5ec7df9319a797c057b5420b578e9467d Mon Sep 17 00:00:00 2001 From: septs Date: Fri, 29 Sep 2023 08:42:57 +0800 Subject: [PATCH] chore: improve subscription userinfo parsing (#781) do not use regex parsing for `Subscription-UserInfo` header field --- adapter/provider/subscription_info.go | 54 ++++++++------------------- 1 file changed, 16 insertions(+), 38 deletions(-) diff --git a/adapter/provider/subscription_info.go b/adapter/provider/subscription_info.go index fc6992e2..8b90601c 100644 --- a/adapter/provider/subscription_info.go +++ b/adapter/provider/subscription_info.go @@ -1,7 +1,6 @@ package provider import ( - "github.com/dlclark/regexp2" "strconv" "strings" ) @@ -13,45 +12,24 @@ type SubscriptionInfo struct { Expire int64 } -func NewSubscriptionInfo(str string) (si *SubscriptionInfo, err error) { - si = &SubscriptionInfo{} - str = strings.ToLower(str) - reTraffic := regexp2.MustCompile("upload=(\\d+); download=(\\d+); total=(\\d+)", 0) - reExpire := regexp2.MustCompile("expire=(\\d+)", 0) - - match, err := reTraffic.FindStringMatch(str) - if err != nil || match == nil { - return nil, err - } - group := match.Groups() - si.Upload, err = str2uint64(group[1].String()) - if err != nil { - return nil, err - } - - si.Download, err = str2uint64(group[2].String()) - if err != nil { - return nil, err - } - - si.Total, err = str2uint64(group[3].String()) - if err != nil { - return nil, err - } - - match, _ = reExpire.FindStringMatch(str) - if match != nil { - group = match.Groups() - si.Expire, err = str2uint64(group[1].String()) +func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo, err error) { + userinfo = strings.ToLower(userinfo) + userinfo = strings.ReplaceAll(userinfo, " ", "") + si = new(SubscriptionInfo) + for _, field := range strings.Split(userinfo, ";") { + switch name, value, _ := strings.Cut(field, "="); name { + case "upload": + si.Upload, err = strconv.ParseInt(value, 10, 64) + case "download": + si.Download, err = strconv.ParseInt(value, 10, 64) + case "total": + si.Total, err = strconv.ParseInt(value, 10, 64) + case "expire": + si.Expire, err = strconv.ParseInt(value, 10, 64) + } if err != nil { - return nil, err + return } } - return } - -func str2uint64(str string) (int64, error) { - i, err := strconv.ParseInt(str, 10, 64) - return i, err -}