Reverse proxy implemented by Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Look at the Golang bag manual when you see Net/http/httputil there is a type reverseproxy, this is not a reverse proxy it! Golang comes with reverse proxy function? Curiosity to try, it is very simple, not a few lines of code to achieve a simple reverse proxy service.

About reverse proxy Baidu Encyclopedia said very detailed, here excerpt the definition:

The reverse proxy method refers to a proxy server that accepts connection requests on the Internet, then forwards the request to a server on the internal network and returns the results from the server to the client requesting the connection on the Internet, Reverse. At this point the proxy server appears as a reverse proxy server externally.

Golang Implementation Code

Package Mainimport ("Log", "Net/http" "Net/http/httputil" "Net/url") type handle struct {host Stringport string}func (this * HANDLE) servehttp (w http. Responsewriter, R *http. Request) {remote, err: = URL. Parse ("http://" + This.host + "+" + this.port) if err! = Nil {panic (err)}proxy: = Httputil. Newsinglehostreverseproxy (remote) proxy. Servehttp (W, R)}func StartServer () {//proxy server host and Porth: = &handle{host: "127.0.0.1", Port: "W"}err: = http. Listenandserve (": 8888", h) if err! = Nil {log. Fatalln ("Listenandserve:", err)}}func main () {StartServer ()}

The key code is Newsinglehostreverseproxy this method, look at the source word is not difficult to see the method returned a Reverseproxy object, in Reverseproxy Servehttp method to achieve this specific process, The primary is to reseal the source HTTP header and then send it to the back-end server.

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.