Код:
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
type Proxy struct {
addr string
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
target := r.RequestURI
targetUri := strings.Split(target, "")
cookies := r.Cookies()
cookiesStr := ""
for _,x := range cookies {
cookiesStr += ", cookie { " + x.Name + " = " + x.Value + " } "
}
if targetUri[0] == "/" {
w.Write([]byte("welcome to http proxy.."))
return
}
switch r.Method {
case "GET":
fmt.Println(r.RequestURI + " " + r.UserAgent() + cookiesStr)
getResponse, getError := http.Get(r.RequestURI)
if getError != nil {
w.Write([]byte("http proxy connection error with " + r.RequestURI + " " + getError.Error()))
return
}
defer getResponse.Body.Close()
getData,_ := ioutil.ReadAll(getResponse.Body)
w.Write(getData)
case "POST":
w.Write([]byte("post proxy!"))
default:
w.Write([]byte("method not supported " + r.Method))
}
}
func main() {
proxy := &Proxy{addr: "0.0.0.0:9090"}
http.ListenAndServe(proxy.addr, proxy)
}