http.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package server
  2. import (
  3. log "code.google.com/p/log4go"
  4. "net"
  5. "ngrok/conn"
  6. )
  7. /**
  8. * Listens for new http connections from the public internet
  9. */
  10. func httpListener(addr *net.TCPAddr) {
  11. // bind/listen for incoming connections
  12. listener, err := net.ListenTCP("tcp", addr)
  13. if err != nil {
  14. panic(err)
  15. }
  16. log.Info("Listening for public http connections on %v", getTCPPort(listener.Addr()))
  17. for {
  18. // accept new public connections
  19. tcpConn, err := listener.AcceptTCP()
  20. if err != nil {
  21. panic(err)
  22. }
  23. // handle the new connection asynchronously
  24. go httpHandler(tcpConn)
  25. }
  26. }
  27. /**
  28. * Handles a new http connection from the public internet
  29. */
  30. func httpHandler(tcpConn net.Conn) {
  31. // wrap up the connection for logging
  32. conn := conn.NewHttp(tcpConn, "pub")
  33. defer conn.Close()
  34. defer func() {
  35. // recover from failures
  36. if r := recover(); r != nil {
  37. conn.Warn("Failed with error %v", r)
  38. }
  39. }()
  40. // read out the http request
  41. req, err := conn.ReadRequest()
  42. if err != nil {
  43. panic(err)
  44. }
  45. conn.Debug("Found hostname %s in request", req.Host)
  46. tunnel := tunnels.Get("http://" + req.Host)
  47. if tunnel == nil {
  48. conn.Info("No tunnel found for hostname %s", req.Host)
  49. return
  50. }
  51. tunnel.HandlePublicConnection(conn)
  52. }