reverseproxy2.go 6.9 KB

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