1 内部服务器代码
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type RealServer struct {
Addr string
}
func (this *RealServer) Run() {
log.Println("真实服务器启动:" + this.Addr)
mux := http.NewServeMux()
mux.HandleFunc("/", this.Hello)
server := &http.Server{
Addr: this.Addr,
WriteTimeout: time.Second * 3,
Handler: mux,
}
go func() {
log.Fatal(server.ListenAndServe())
}()
}
func (this *RealServer) Hello(w http.ResponseWriter, r *http.Request) {
// 127.0.0.1:8008/abc?sd=1
// this.Addr = 127.0.0.1:8008
// r.URL.Path = /abc
urlPath := fmt.Sprintf("http://%s%s\n", this.Addr, r.URL.Path)
_, _ = io.WriteString(w, urlPath)
}
func main() {
rs1 := &RealServer{Addr: "127.0.0.1:2003"}
rs1.Run()
rs2 := &RealServer{Addr: "127.0.0.1:2004"}
rs2.Run()
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
}
2 反向代理服务器代码
package main
import (
"bufio"
"log"
"net/http"
"net/url"
)
var (
proxy_addr = "http://127.0.0.1:2003" // 内部服务器IP和地址
port = "2002" // nginx反向代理服务器的端口为2002, 作为服务器2003的代理
)
func handler(w http.ResponseWriter, r *http.Request) {
// 解析代理地址, 更改请求体的协议和主机
proxy, err := url.Parse(proxy_addr)
r.URL.Scheme = proxy.Scheme
r.URL.Host = proxy.Host
// 请求下游
transport := http.DefaultTransport
resp, err := transport.RoundTrip(r)
if err != nil {
log.Print(err)
return
}
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
defer resp.Body.Close()
_, _ = bufio.NewReader(resp.Body).WriteTo(w)
}
func main() {
http.HandleFunc("/", handler)
log.Println("start serving on port "+ port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatal(err)
}
}