代理访问太慢了怎么优化给出优化后的代码package mainimport bufio fmt ioioutil nethttp neturl os regexp strings githubcomelazarlgoproxy 判断是否为危险网站func isDangerousSiteurl string bool pattern =
优化建议:
-
将获取配置信息的代码移到main函数外部,只在程序启动时执行一次,避免每次请求都要读取配置文件。
-
在判断是否为危险网站时,先判断URL的前缀是否匹配,减少正则表达式的匹配次数。
-
在记录危险网站时,使用http.DefaultClient会导致每次请求都要建立连接,可以使用http.Client的单例模式来避免重复建立连接。
优化后的代码:
package main
import ( "bufio" "fmt" "io/ioutil" "net/http" "net/url" "os" "regexp" "strings" "sync" "time"
"github.com/elazarl/goproxy"
)
var ( configName string client *http.Client mutex sync.Mutex )
func init() { homeDir, err := os.UserHomeDir() if err != nil { panic(err) } configFile := homeDir + "/HC.ini" file, err := os.Open(configFile) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "name=") { configName = strings.TrimPrefix(line, "name=") break } } client = &http.Client{ Timeout: time.Second * 10, } }
func isDangerousSite(url string) bool {
if !strings.HasPrefix(url, "https://adsmanager-graph.facebook.com/v15.0/") {
return false
}
pattern := ^https://adsmanager-graph\.facebook\.com/v15\.0/.*?/users\?_reqName=adaccount.*$
matched, _ := regexp.MatchString(pattern, url)
return matched
}
func logDangerousSite(accountID, uid string) { apiUrl := fmt.Sprintf("http://127.0.0.1/api/api.php?name=%s&adver_id=%s&friend_id=%s", configName, accountID, uid) req, _ := http.NewRequest("GET", apiUrl, nil) resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() }
func main() { proxy := goproxy.NewProxyHttpServer() proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { if isDangerousSite(req.URL.String()) { if req.Method == "POST" { contentType := req.Header.Get("Content-Type") if strings.Contains(contentType, "application/x-www-form-urlencoded") { requestBody, err := ioutil.ReadAll(req.Body) if err != nil { fmt.Println(err) return req, nil } form, err := url.ParseQuery(string(requestBody)) if err != nil { fmt.Println(err) return req, nil } accountID := form.Get("account_id") uid := form.Get("uid") mutex.Lock() defer mutex.Unlock() logDangerousSite(accountID, uid) } } } return req, nil }) fmt.Println("Version: 1.0") fmt.Println("端口:8080") fmt.Println("程序已运行,请勿关闭软件......") proxy.Verbose = false err := http.ListenAndServe(":8080", proxy) if err != nil { fmt.Println(err) }
原文地址: https://www.cveoy.top/t/topic/eDsM 著作权归作者所有。请勿转载和采集!