首页 价格 教程中心 图形识别new

免费送1G流量

CN
Golang实现HTTP代理服务。

使用Go语言中的标准库 net/http 来实现;

代码如下:

package main
import (
    "io"
    "log"
    "net/http"

)

func handleHTTP(w http.ResponseWriter, req *http.Request) {
    resp, err := http.DefaultTransport.RoundTrip(req)
    if err != nil {
        http.Error(w, err.Error(), http.StatusServiceUnavailable)
        return
    }
    defer resp.Body.Close()
    copyHeader(w.Header(), resp.Header)
    w.WriteHeader(resp.StatusCode)
    io.Copy(w, resp.Body)
}
func copyHeader(dst, src http.Header) {
    for k, vv := range src {
        for _, v := range vv {
            dst.Add(k, v)
        }
    }
}

func main() {

    server := &http.Server{
        Addr: "127.0.0.1:8080",
        Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            handleHTTP(w, r)
        }),
    }

    log.Fatal(server.ListenAndServe())
}
Go

测试

写了一段python代码,用于测试代理服务程序:

import requests

url = "http://baidu.com"

proxies = {'http':"127.0.0.1:8080"}

resp = requests.get(url,proxies=proxies)

print(resp.status_code)
print(resp.text)
Go

程序运行结果:

200
<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>