爱包子的鱼

Open Source, Open Mind,
Open Sight, Open Future!

Golang中的反向代理

Golang中的反向代理

package main

import (
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

type handler struct {
	host  string
	port  string
	proxy http.Handler
}

func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Printf("%s %s %s\n", r.Method, r.URL, r.Host)
	h.proxy.ServeHTTP(w, r)
}

func newHandler(host, port string) *handler {
	h := &handler{
		host: host,
		port: port,
	}
	remote, err := url.Parse("http://" + h.host + ":" + h.port)
	if err != nil {
		panic(err)
	}
	h.proxy = httputil.NewSingleHostReverseProxy(remote)
	return h
}

func main() {
	h := newHandler("127.0.0.1", "80")
	err := http.ListenAndServe(":8000", h)
	if err != nil {
		log.Fatalln("ListenAndServe: ", err)
	}
}


标题:Golang中的反向代理
作者:JoeysCat
地址:http://oook.fun/articles/2020/11/19/1605751002046.html