1 内部服务器代码

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "syscall"
  10. "time"
  11. )
  12. type RealServer struct {
  13. Addr string
  14. }
  15. func (this *RealServer) Run() {
  16. log.Println("真实服务器启动:" + this.Addr)
  17. mux := http.NewServeMux()
  18. mux.HandleFunc("/", this.Hello)
  19. server := &http.Server{
  20. Addr: this.Addr,
  21. WriteTimeout: time.Second * 3,
  22. Handler: mux,
  23. }
  24. go func() {
  25. log.Fatal(server.ListenAndServe())
  26. }()
  27. }
  28. func (this *RealServer) Hello(w http.ResponseWriter, r *http.Request) {
  29. // 127.0.0.1:8008/abc?sd=1
  30. // this.Addr = 127.0.0.1:8008
  31. // r.URL.Path = /abc
  32. urlPath := fmt.Sprintf("http://%s%s\n", this.Addr, r.URL.Path)
  33. _, _ = io.WriteString(w, urlPath)
  34. }
  35. func main() {
  36. rs1 := &RealServer{Addr: "127.0.0.1:2003"}
  37. rs1.Run()
  38. rs2 := &RealServer{Addr: "127.0.0.1:2004"}
  39. rs2.Run()
  40. quit := make(chan os.Signal)
  41. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  42. <-quit
  43. }

2 反向代理服务器代码

  1. package main
  2. import (
  3. "bufio"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. )
  8. var (
  9. proxy_addr = "http://127.0.0.1:2003" // 内部服务器IP和地址
  10. port = "2002" // nginx反向代理服务器的端口为2002, 作为服务器2003的代理
  11. )
  12. func handler(w http.ResponseWriter, r *http.Request) {
  13. // 解析代理地址, 更改请求体的协议和主机
  14. proxy, err := url.Parse(proxy_addr)
  15. r.URL.Scheme = proxy.Scheme
  16. r.URL.Host = proxy.Host
  17. // 请求下游
  18. transport := http.DefaultTransport
  19. resp, err := transport.RoundTrip(r)
  20. if err != nil {
  21. log.Print(err)
  22. return
  23. }
  24. for k, vv := range resp.Header {
  25. for _, v := range vv {
  26. w.Header().Add(k, v)
  27. }
  28. }
  29. defer resp.Body.Close()
  30. _, _ = bufio.NewReader(resp.Body).WriteTo(w)
  31. }
  32. func main() {
  33. http.HandleFunc("/", handler)
  34. log.Println("start serving on port "+ port)
  35. err := http.ListenAndServe(":"+port, nil)
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. }