Go Proxy Server code
Recently used abandoned small notebook built a CentOS server hangs, took the SSH,TOMCAT,GO environment, want to take a proxy server access routing, do not want to install, want to write one, by the way to review the go language knowledge.
In the beginning, I searched the Internet. Go Language agent for the proxy server, search for a:
From: http://symphony.b3log.org/article/1357452978419
(Original address: Http://kejibo.com/golang-http-proxy-server has expired)
Package Mainimport ("http" "Log" "OS" "Io/ioutil") Func Handler (W http. Responsewriter, R *http. Request) {resp, err: = http. Defaultclient. do(r) Defer resp. Body. Close() if err! = Nil {panic (err)} for K, V: = Range resp. Header{for _, VV: = Range v {w. Header(). ADD(k, VV)} } for _, c: = Range resp. Setcookie{W. Header(). ADD("Set-cookie"C. Raw)} W. Writeheader(RESP. StatusCode) result, err: = Ioutil. ReadAll(RESP. Body) If err! = Nil && Err! = OS. EOF{Panic (err)} W. Write(Result)} Func main () {HTTP. Handlefunc("/", handler) log. Println("Start serving on port 8888") HTTP. Listenandserve(": 8888", nil) OS. Exit(0)}
Written file uploaded to the server, go build test.go compiled, found resp. Setcookie does not have this method, the compilation does not pass, the above article said it to the latest HTTP source code and compiled to go source, I was shocked, but also to modify its source Ah, I looked under their own go language version, Is 1.4.2, is 15 this year's, he writes the article The time is 13, hehe, my more new than his, how may be old?! And he said that compiling the source code, is how complex AH ~
thus Witty me, in order to compile through, live to annotate it.
Go Build Test.go
Okay, compile through, execute it
/.test
Display turned on, or to confirm, scan the port, looked at the next really open.
Seems to have finished, so go to the browser set up the agent, open baidu.com, he told me the method is wrong, I looked at the printing information, found
Defer resp. Body.close ()
This line reported the mistake:
Invalid memory address or nil pointer dereference
The net looked for a bit, originally is the RESP variable null pointer error.
I try to print the ERR message again:
Http:Request.RequestURI can ' t is set in client requests.
That means, TTP. Defaultclient.do (R) This usage is not correct, it cannot be set, so I found a replacement: http. Newrequest, its advantage is can get also can post, should have put and so on operation, did not try.
So this paragraph of handler function was changed by my patience to this:
Func Handler (w http. Responsewriter, R *http. Request) {FMT. Println("URL:"R. RequestUri) FMT. Println("Method:"R. Method) FMT. Println("header:"R. Header) Client0: = &http. Client{} req, _: = http. Newrequest(r. MethodR. RequestUriR. Body) FMT. Printf("send:%+v\n", req)//Look under the Sent structure resp, err: = Client0. do(req)//Send if Err!=nil {FMT. Println("Error:", err)} Defer resp. Body. Close() for _, Value: = Range resp. Request. Cookies() {W. Header(). ADD(Value. Name, value. Value)} for K, V: = Range resp. Header{for _, VV: = Range v {w. Header(). ADD(k, VV)} } W. Writeheader(RESP. StatusCode) result, err: = Ioutil. ReadAll(RESP. Body) if (err! = nil) {FMT. Println("Error:", err)} FMT. Println("Result:", result);_,err = W. Write(result) if (err! = nil) {FMT. Println("Error:", err)}
I actually edited on a Mac computer, and the server upload was too slow to compile (= =,
) and the code seems to be writing pretty good looks.
run up, visit Baidu dead Loop, I changed a few times, see a few times, or so, helpless I had to test other sites, the test site is my one simple JSP page, on a simple list, I visited, unexpectedly quickly appeared, unexpectedly successfully visited, But I did not change to what code ah, I seriously think of a thought, should be visited Baidu when not put the request head past, Cause it to visit baidu.com, the source of the link is post access, and are baidu.com, in order to confirm my conjecture, I added a request for the first cookie up
...... req, _ := http.NewRequest(r.Method, r.RequestURI, r.Body) for k, v := range req.Header { for _, vv := range v { r.Header.Add(k, vv) } } for _, value := range req.Cookies() { r.Header.Add(value.Name,value.Value) }......
Compile run, the browser re-refresh, unexpectedly suddenly hit, my guess turns out to be correct.
The server basically completed, into the test phase, first Baidu, success, but some of the picture has opened, in the other, csdn can access, picture problems, Sina Normal, Oschina Normal, is Baidu that picture load cracked. Readers are interested in their own research, in this, I just first put a simple proxy server, convenient for everyone to use.
Finally, we browsed the code of the Rectification Proxy server:
Package Mainimport ("Net/http" "Log" "Io/ioutil"//"IO" "FMT") Func Handler (W http. Responsewriter, R *http. Request) {//HTTP. Defaultclient.//W. Write([]byte ("dddd") FMT. Println("URL:"R. RequestUri) FMT. Println("Method:"R. Method) FMT. Println("header:"R. Header) Client0: = &http. Client{} req, _: = http. Newrequest(r. MethodR. RequestUriR. Body) for k, V: = Range req. Header{for _, VV: = range V {r. Header. ADD(k, VV)} } for _, Value: = Range req. Cookies() {R. Header. ADD(Value. Name, value. Value)} FMT. Printf("send:%+v\n", req)//Look under the Sent structure resp, err: = Client0. do(req)//Send if Err!=nil {FMT. Println("Error:", err)} Defer resp. Body. Close() for _, Value: = Range resp. Request. Cookies() {W. Header(). ADD(Value. Name, value. Value)} for K, V: = Range resp. Header{for _, VV: = Range v {w. Header(). ADD(k, VV)} } W. Writeheader(RESP. StatusCode) result, err: = Ioutil. ReadAll(RESP. Body) if (err! = nil) {FMT. Println("Error:", err)} FMT. Println("Result:", result);_,err = W. Write(result) if (err! = nil) {FMT. Println("Error:", err)}}func Main () {HTTP. Handlefunc("/", handler) log. Println("Start serving on port 8089") HTTP. Listenandserve(": 8089", nil) Log. Println("Server Start")}
Look at the code you changed, and the person on the Internet code, the original difference so much, look at the cry.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Go Proxy Server code