reverseproxy.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // HTTP reverse proxy handler
  5. package main
  6. import (
  7. "io"
  8. "log"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "time"
  13. "flag"
  14. "compress/gzip"
  15. )
  16. var rawurl = flag.String("url", "https://trade.lmaxtrader.com", "lmax trade url")
  17. var host = flag.String("http", ":8088", "sever port")
  18. /*
  19. func setNoDelayAddress(conn net.Conn) {
  20. file, _ := conn.(*net.TCPConn).File()
  21. fd := file.Fd()
  22. syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.TCP_NODELAY, 1);
  23. }
  24. */
  25. func main() {
  26. flag.Parse()
  27. myHandler, err := NewHostReverseProxy(*rawurl)
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. s := &http.Server{
  32. Addr : *host,
  33. Handler: myHandler,
  34. }
  35. //创建Listen
  36. log.Fatal(s.ListenAndServeTLS("certs/server.pem", "certs/server.key"))
  37. }
  38. func NewHostReverseProxy(rawurl string) (*ReverseProxy, error) {
  39. u, err := url.Parse(rawurl)
  40. if err != nil {
  41. return nil, err
  42. }
  43. proxy := NewSingleHostReverseProxy(u)
  44. proxy.FlushInterval = time.Second
  45. return proxy, nil
  46. }
  47. // onExitFlushLoop is a callback set by tests to detect the state of the
  48. // flushLoop() goroutine.
  49. var onExitFlushLoop func()
  50. // ReverseProxy is an HTTP Handler that takes an incoming request and
  51. // sends it to another server, proxying the response back to the
  52. // client.
  53. type ReverseProxy struct {
  54. // Director must be a function which modifies
  55. // the request into a new request to be sent
  56. // using Transport. Its response is then copied
  57. // back to the original client unmodified.
  58. Director func(*http.Request)
  59. // The transport used to perform proxy requests.
  60. // If nil, http.DefaultTransport is used.
  61. Transport http.RoundTripper
  62. // FlushInterval specifies the flush interval
  63. // to flush to the client while copying the
  64. // response body.
  65. // If zero, no periodic flushing is done.
  66. FlushInterval time.Duration
  67. }
  68. func singleJoiningSlash(a, b string) string {
  69. aslash := strings.HasSuffix(a, "/")
  70. bslash := strings.HasPrefix(b, "/")
  71. switch {
  72. case aslash && bslash:
  73. return a + b[1:]
  74. case !aslash && !bslash:
  75. return a + "/" + b
  76. }
  77. return a + b
  78. }
  79. // NewSingleHostReverseProxy returns a new ReverseProxy that rewrites
  80. // URLs to the scheme, host, and base path provided in target. If the
  81. // target's path is "/base" and the incoming request was for "/dir",
  82. // the target request will be for /base/dir.
  83. func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
  84. targetQuery := target.RawQuery
  85. director := func(req *http.Request) {
  86. req.URL.Scheme = target.Scheme
  87. req.URL.Host = target.Host
  88. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  89. if targetQuery == "" || req.URL.RawQuery == "" {
  90. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  91. } else {
  92. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  93. }
  94. }
  95. return &ReverseProxy{Director: director}
  96. }
  97. func copyHeader(dst, src http.Header) {
  98. for k, vv := range src {
  99. for _, v := range vv {
  100. dst.Add(k, v)
  101. }
  102. }
  103. }
  104. // Hop-by-hop headers. These are removed when sent to the backend.
  105. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  106. var hopHeaders = []string{
  107. "Connection",
  108. "Keep-Alive",
  109. "Proxy-Authenticate",
  110. "Proxy-Authorization",
  111. "Te", // canonicalized version of "TE"
  112. "Trailers",
  113. "Transfer-Encoding",
  114. "Upgrade",
  115. }
  116. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  117. transport := p.Transport
  118. if transport == nil {
  119. transport = http.DefaultTransport
  120. }
  121. outreq := new(http.Request)
  122. *outreq = *req // includes shallow copies of maps, but okay
  123. p.Director(outreq)
  124. outreq.Proto = "HTTP/1.1"
  125. outreq.ProtoMajor = 1
  126. outreq.ProtoMinor = 1
  127. outreq.Close = false
  128. // Remove hop-by-hop headers to the backend. Especially
  129. // important is "Connection" because we want a persistent
  130. // connection, regardless of what the client sent to us. This
  131. // is modifying the same underlying map from req (shallow
  132. // copied above) so we only copy it if necessary.
  133. copiedHeaders := false
  134. for _, h := range hopHeaders {
  135. if outreq.Header.Get(h) != "" {
  136. if !copiedHeaders {
  137. outreq.Header = make(http.Header)
  138. copyHeader(outreq.Header, req.Header)
  139. copiedHeaders = true
  140. }
  141. outreq.Header.Del(h)
  142. }
  143. }
  144. res, err := transport.RoundTrip(outreq)
  145. if err != nil {
  146. log.Printf("http: proxy error: %v", err)
  147. rw.WriteHeader(http.StatusInternalServerError)
  148. return
  149. }
  150. defer res.Body.Close()
  151. copyHeader(rw.Header(), res.Header)
  152. //判断是否需要压缩
  153. if rw.Header().Get("Content-Encoding") != "gzip" {
  154. rw.Header().Set("Content-Encoding", "gzip")
  155. rw.WriteHeader(res.StatusCode)
  156. gz , _ := gzip.NewWriterLevel(rw, gzip.BestCompression)
  157. defer gz.Close()
  158. p.copyResponse(gzipResponseWriter{Writer: gz, ResponseWriter: rw}, res.Body)
  159. return
  160. }
  161. rw.WriteHeader(res.StatusCode)
  162. p.copyResponse(rw, res.Body)
  163. }
  164. type gzipResponseWriter struct {
  165. io.Writer
  166. http.ResponseWriter
  167. }
  168. func (w gzipResponseWriter) Write(b []byte) (int, error) {
  169. return w.Writer.Write(b)
  170. }
  171. func (w gzipResponseWriter) Flush() {
  172. w.Writer.(*gzip.Writer).Flush()
  173. w.ResponseWriter.(http.Flusher).Flush()
  174. }
  175. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) (err error) {
  176. buf := make([]byte, 32*1024)
  177. for {
  178. nr, er := src.Read(buf)
  179. if nr > 0 {
  180. nw, ew := dst.Write(buf[0:nr])
  181. if ew != nil {
  182. err = ew
  183. break
  184. }
  185. if nr != nw {
  186. err = io.ErrShortWrite
  187. break
  188. }
  189. dst.(http.Flusher).Flush()
  190. }
  191. if er == io.EOF {
  192. break
  193. }
  194. if er != nil {
  195. err = er
  196. break
  197. }
  198. }
  199. return nil
  200. }
  201. type writeFlusher interface {
  202. io.Writer
  203. http.Flusher
  204. }