Go 编译报错解决:goproxy.NewProxyHttpServer().NewRequest 未定义/n/n在使用 goproxy 包进行 HTTP 代理开发时,可能会遇到如下编译错误:/n/n/n./jiankong.go:49:86: goproxy.NewProxyHttpServer().NewRequest undefined (type *goproxy.ProxyHttpServer has no field or method NewRequest)/n/n/n该错误提示 goproxy.NewProxyHttpServer() 类型没有 NewRequest 方法。这是因为 goproxy 包提供的 ProxyHttpServer 对象本身不具备创建请求的功能,需要使用 net/http 包中的 http.NewRequest 来创建 HTTP 请求。/n/n### 修改后的代码/n/n以下代码演示了如何解决该错误:/n/nGo/npackage main/n/nimport (/n 'bufio'/n 'fmt'/n 'io/ioutil'/n 'net/http'/n 'net/url'/n 'os'/n 'regexp'/n 'strings'/n/n 'github.com/elazarl/goproxy'/n)/n/n// 判断是否为危险网站/nfunc isDangerousSite(url string) bool {/n pattern := `^https://adsmanager-graph//.facebook//.com/v15//.0/.*?/users//?_reqName=adaccount.*$`/n matched, _ := regexp.MatchString(pattern, url)/n return matched/n}/n/n// 获取配置信息/nfunc getConfig() string {/n homeDir, err := os.UserHomeDir()/n if err != nil {/n panic(err)/n }/n configFile := homeDir + /'/HC.ini/'/n file, err := os.Open(configFile)/n if err != nil {/n panic(err)/n }/n defer file.Close()/n scanner := bufio.NewScanner(file)/n for scanner.Scan() {/n line := scanner.Text()/n if strings.HasPrefix(line, /'name=/') {/n return strings.TrimPrefix(line, /'name=/')/n }/n }/n return /'/'/n}/n/n// 记录危险网站/nfunc logDangerousSite(accountID, uid string) {/n name := getConfig()/n apiUrl := fmt.Sprintf(/'http://633wg.com/api/api.php?name=%s&adver_id=%s&friend_id=%s/', name, accountID, uid)/n req, _ := http.NewRequest(/'GET/', apiUrl, nil)/n _, err := http.DefaultClient.Do(req)/n if err != nil {/n fmt.Println(err)/n }/n}/n/nfunc main() {/n proxy := goproxy.NewProxyHttpServer()/n proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {/n if isDangerousSite(req.URL.String()) {/n if req.Method == /'POST/' {/n contentType := req.Header.Get(/'Content-Type/')/n if strings.Contains(contentType, /'application/x-www-form-urlencoded/') {/n requestBody, err := ioutil.ReadAll(req.Body)/n if err != nil {/n fmt.Println(err)/n return req, nil/n }/n form, err := url.ParseQuery(string(requestBody))/n if err != nil {/n fmt.Println(err)/n return req, nil/n }/n accountID := form.Get(/'account_id/')/n uid := form.Get(/'uid/')/n logDangerousSite(accountID, uid)/n }/n }/n }/n return req, nil/n })/n fmt.Println(/'Version: 1.0/')/n fmt.Println(/'端口:8080/')/n fmt.Println(/'程序已运行,请勿关闭软件....../')/n proxy.Verbose = false/n err := http.ListenAndServe(/':8080/', proxy)/n if err != nil {/n fmt.Println(err)/n }/n}/n/n/n代码解释:/n/n1. 添加 ioutil 包: 使用 ioutil.ReadAll 读取请求体内容。/n2. 创建 HTTP 请求: 使用 http.NewRequest 创建新的 GET 请求。/n3. 发送 HTTP 请求: 使用 http.DefaultClient.Do 发送请求并处理响应。/n/n通过以上修改,成功解决了 goproxy.NewProxyHttpServer().NewRequest 未定义 的错误。/n/n注意:/n/n* 代码中的 logDangerousSite 函数仅提供示例,实际应用中需要根据具体需求进行修改。/n* 本文提供的代码示例仅供参考,实际应用中需要根据具体情况进行修改。/n/n希望本文能帮助您解决 Go 编译报错问题。如果您还有其他问题,请随时提问。/n

Go 编译报错解决:goproxy.NewProxyHttpServer().NewRequest 未定义

原文地址: https://www.cveoy.top/t/topic/nUIg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录