-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
76 lines (64 loc) · 1.92 KB
/
server.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
// server.go - AMP tunnel server related functions.
//
// To the extent possible under law, Ivan Markin waived all copyright
// and related or neighboring rights to this module of amper, using the creative
// commons "CC0" public domain dedication. See LICENSE or
// <http://creativecommons.org/publicdomain/zero/1.0/> for full details.
package amper
import (
"io"
"net/http"
ampcodec "github.com/nogoegst/amper/codec/amp"
getcodec "github.com/nogoegst/amper/codec/get"
)
type Handler interface {
Handle(w io.Writer, r io.Reader) error
}
type handlerFunc struct {
hf func(w io.Writer, r io.Reader) error
}
func (h handlerFunc) Handle(w io.Writer, r io.Reader) error {
return h.hf(w, r)
}
// Handler wraps a handle function hf into Handler.
func HandlerFunc(hf func(w io.Writer, r io.Reader) error) Handler {
return handlerFunc{hf: hf}
}
var (
// Google AMP subnets
allowedSubnets = []string{
"66.249.64.0/19",
"66.102.0.0/20",
}
)
type Server struct {
// Handler to handle requests
Handler Handler
// Allow non-AMP remotes
AllowAllRemotes bool
// UseOldBoilerplate makes AMP encoder use
// deprecated AMP boilerplate. As it's much shorter
// than the new one, one may benefit from using it
// to save some bandwidth.
// Note that it may stop working in future.
UseOldAMPBoilerplate bool
}
func (ah *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// We want to give a hint to AMP cache that this is request
// will not be used anymore.
w.Header().Set("Cache-Control", "private, max-age=0")
// We always write AMP page even if it has no useful data.
enc := ampcodec.NewEncoder(w)
enc.UseOldBoilerplate = ah.UseOldAMPBoilerplate
defer enc.Close()
// We do not throw any HTTP errors because clients are not going
// to get them anyway (because of the cache middleware).
req, err := getcodec.Decode(r.URL.Path)
if err != nil {
return
}
err = ah.Handler.Handle(enc, req)
if err != nil {
return
}
}