Golang Crawl Pit: A simple HTTP intra-network forwarding

Source: Internet
Author: User

Recently, there is a need to request data from a port on the intranet server, the problem is that the intranet port cannot be accessed by the extranet, so a forwarding agent service is required. The principle is that when the request arrives, the address of the local machine is replaced with the destination address, and then the other format is unchanged, and the target message header and message are returned to the client after the target request is returned. The specific code is as follows:

Func main () {localhost: = "127.0.0.1:9001" targethost: = "127.0.0.1:8001" Httpsserver (LocalHost, Targethost) Log. Error ("HTTP Server down!!!")} Func httpsserver (addr string, remote_addr string) {http. Handlefunc ("/", Func (w http.) Responsewriter, req *http. Request) {cli: = &http. client{} Body: = Make ([]byte, 0) n, err: = Io. Readfull (req. Body, body) if err! = nil {io. WriteString (W, "Request Data Error") return} Requrl: = "/http" + REMOTE_ADDR + req. Url. Path req2, Err: = http. Newrequest (req. Method, Requrl, strings. Newreader (String (body))) If err! = nil {io. WriteString (W, "Request Error") return}//Set Request content type ContentType: = req. Header.get ("Content-type") req2. Header.set ("Content-type", ContentType)//Request REP2, err: = CLI. Do (REQ2) if err! = nil {io.            WriteString (W, "Not found!") REturn} defer REP2. Body.close () n, err = io. Readfull (REP2. Body, body) if err! = nil {io. WriteString (W, "Request Error") return}//Set response header for k, V: = Range rep2. Header {W.header (). Set (k, v[0])} io. WriteString (W, String (Body[:n]))}) var err error = Nil Err = http. Listenandserve (": 12307", nil) if err! = Nil {log.    Fatal ("Server Down!!!") }}

  

At this point, a simple proxy service is completed.

Golang Crawl Pit: A simple HTTP intra-network forwarding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.