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