func httpHandler(c conn.Conn, proto string) {
	defer c.Close()
	defer func() {
		if r := recover(); r != nil {
			c.Warn("httpHandler failed with error %v", r)
		}
	}()
	c.SetDeadline(time.Now().Add(connReadTimeout))
	vhostConn, err := vhost.HTTP(c)
	if err != nil {
		c.Warn("Failed to read valid %s request: %v", proto, err)
		c.Write([]byte(BadRequest))
		return
	}
	host := strings.ToLower(vhostConn.Host())
	auth := vhostConn.Request.Header.Get("Authorization")
	vhostConn.Free()
	c = conn.Wrap(vhostConn, "pub")
	c.Debug("Found hostname %s in request", host)
	tunnel := tunnelRegistry.Get(fmt.Sprintf("%s://%s", proto, host))
	if tunnel == nil {
		c.Info("No tunnel found for hostname %s", host)
		c.Write([]byte(fmt.Sprintf(NotFound, len(host)+18, host)))
		return
	}
	if tunnel.req.HttpAuth != "" && auth != tunnel.req.HttpAuth {
		c.Info("Authentication failed: %s", auth)
		c.Write([]byte(NotAuthorized))
		return
	}
	c.SetDeadline(time.Time{})
	tunnel.HandlePublicConnection(c)
}
Handles a new http connection from the public internet
package server
import (
	"crypto/tls"
	"fmt"
	vhost "zach-rock/vhost"
	"strings"
	"time"
	"zach-rock/conn"
	"zach-rock/log"
)
const (
	NotAuthorized = `HTTP/1.0 401 Not Authorized
WWW-Authenticate: Basic realm="zach-rock"
Content-Length: 23
Authorization required
`
	NotFound = `HTTP/1.0 404 Not Found
Content-Length: %d
Tunnel %s not found
`
	BadRequest = `HTTP/1.0 400 Bad Request
Content-Length: 12
Bad Request
`
)
func startHttpListener(addr string, tlsCfg *tls.Config) (listener *conn.Listener) {
	var err error
	if listener, err = conn.Listen(addr, "pub", tlsCfg); err != nil {
		panic(err)
	}
	proto := "http"
	if tlsCfg != nil {
		proto = "https"
	}
	log.Info("Listening for public %s connections on %v", proto, listener.Addr.String())
	go func() {
		for conn := range listener.Conns {
			go httpHandler(conn, proto)
		}
	}()
	return
}