启动服务
mux := http.NewServeMux() mux.HandleFunc("/", handler) srv := &http.Server{ Addr: ":2222", Handler: mux, } srv.ListenAndServe()
转发http请求
func handler(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } req.Body = ioutil.NopCloser(bytes.NewReader(body)) url := fmt.Sprintf("%s://%s%s", "http", "xxx.com", req.RequestURI) proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body)) //头信息拷贝 proxyReq.Header = make(http.Header) for h, val := range req.Header { proxyReq.Header[h] = val } //头信息修正 //proxyReq.Header.Set("Authorization", "xxx") //proxyReq.Header.Set("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36") //proxyReq.Header.Set("Host","xxx") //proxyReq.Header.Set("Origin","xxx") //proxyReq.Header.Set("Referer","xxx") httpClient := &http.Client{} resp, err := httpClient.Do(proxyReq) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } defer resp.Body.Close() //拷贝返回体 for name, values := range resp.Header { w.Header()[name] = values } w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(resp.StatusCode) io.Copy(w, resp.Body) }
参考:
...