Skip to content

Commit

Permalink
Added a auto-redirect for HTTP requests
Browse files Browse the repository at this point in the history
  • Loading branch information
surma committed Jan 3, 2017
1 parent 60e24e7 commit add6762
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions simplehttp2server.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ func main() {
if err != nil {
log.Fatalf("Error opening socket: %s", err)
}
ln = &HijackHTTPListener{ln}

tlsListener := tls.NewListener(ln, server.TLSConfig)
tcl := tlsListener
Expand All @@ -151,6 +152,67 @@ func main() {
}
}

type Conn struct {
net.Conn
b byte
e error
f bool
}

func (c *Conn) Read(b []byte) (int, error) {
if c.f {
c.f = false
b[0] = c.b
if len(b) > 1 && c.e == nil {
n, e := c.Conn.Read(b[1:])
if e != nil {
c.Conn.Close()
}
return n + 1, e
} else {
return 1, c.e
}
}
return c.Conn.Read(b)
}

type HijackHTTPListener struct {
net.Listener
}

func (l *HijackHTTPListener) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}

b := make([]byte, 1)
_, err = c.Read(b)
if err != nil {
c.Close()
if err != io.EOF {
return nil, err
}
}

con := &Conn{
Conn: c,
b: b[0],
e: err,
f: true,
}

// First byte == 22 means it's HTTPS
if b[0] == 22 {
return con, nil
}

// Otherwise it’s HTTPS
con.Write([]byte(fmt.Sprintf("HTTP/1.1 301 Moved Permanently\nLocation: https://%s/\n", *listen)))
con.Close()
return con, nil
}

func pushResources(w http.ResponseWriter, r *http.Request) {
pushMap, err := readPushMap(*pushManifest)
if err != nil {
Expand Down

0 comments on commit add6762

Please sign in to comment.