-
Notifications
You must be signed in to change notification settings - Fork 98
/
simplehttp2server.go
137 lines (121 loc) · 3.55 KB
/
simplehttp2server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Copyright 2015 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"crypto/tls"
"flag"
"log"
"mime"
"net"
"net/http"
"regexp"
"strings"
"time"
"github.com/NYTimes/gziphandler"
)
const (
PushMarkerHeader = "X-Is-A-Push"
)
var (
listen = flag.String("listen", ":5000", "Port to listen on")
cors = flag.String("cors", "*", "Set allowed origins")
config = flag.String("config", "", "Config file")
)
func main() {
flag.Parse()
server := &http.Server{
Addr: *listen,
ReadTimeout: 1 * time.Minute,
WriteTimeout: 1 * time.Minute,
TLSConfig: &tls.Config{
NextProtos: []string{"h2", "h2-14"},
PreferServerCipherSuites: true,
},
}
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", *cors)
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTION, HEAD, PATCH, PUT, POST, DELETE")
log.Printf("Request for %s (Accept-Encoding: %s)", r.URL.Path, r.Header.Get("Accept-Encoding"))
dir := "."
redirected := false
if *config != "" {
dir, redirected = processWithConfig(w, r, *config)
}
if redirected {
return
}
if r.Header.Get(PushMarkerHeader) == "" {
pushResources(w)
}
// Add GZIP compression if it is a text-based format
fs := http.FileServer(http.Dir(dir))
typ := mime.TypeByExtension(r.URL.Path)
switch {
case strings.HasPrefix(typ, "text/"):
fallthrough
case typ == "application/xml":
fallthrough
case typ == "":
fs = gziphandler.GzipHandler(fs)
}
fs.ServeHTTP(w, r)
})
if err := configureTLS(server); err != nil {
log.Fatalf("Error configuring TLS: %s", err)
}
ln, err := net.Listen("tcp", server.Addr)
if err != nil {
log.Fatalf("Error opening socket: %s", err)
}
ln = &HijackHTTPListener{ln}
tlsListener := tls.NewListener(ln, server.TLSConfig)
tcl := tlsListener
if strings.HasPrefix(*listen, ":") {
*listen = "localhost" + *listen
}
log.Printf("Listening on https://%s...", *listen)
if err := server.Serve(tcl); err != nil {
log.Fatalf("Error starting webserver: %s", err)
}
}
func pushResources(w http.ResponseWriter) {
linkHeader := w.Header().Get("Link")
parts := strings.Split(linkHeader, ",")
pusher, ok := w.(http.Pusher)
if !ok {
log.Printf("ResponseWriter is not a Pusher. Not pushing anything")
return
}
newParts := []string{}
for _, part := range parts {
if !strings.Contains(part, "rel=preload") {
newParts = append(newParts, part)
continue
}
resource := extractResourceFromLinkHeader(part)
if !strings.HasPrefix(resource, "/") {
log.Printf("--> Push attempt: Resource path needs to start with /")
continue
}
log.Printf("--> Push: %s", resource)
pusher.Push(resource, &http.PushOptions{
Method: "GET",
Header: http.Header{
PushMarkerHeader: []string{"true"},
},
})
}
w.Header().Set("Link", strings.Join(newParts, ","))
}
var extractionRegexp = regexp.MustCompile("<([^>]+)>")
func extractResourceFromLinkHeader(part string) string {
return extractionRegexp.FindStringSubmatch(part)[1]
}