Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
157 lines (136 loc) · 3.83 KB
/
Copy pathmain.go
File metadata and controls
157 lines (136 loc) · 3.83 KB
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package main
import (
"context"
"errors"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"time"
)
const upstreamBase = "https://sugang.snu.ac.kr"
const statusClientClosedRequest = 499
var allowedAction = regexp.MustCompile(`^cc1\d{2}(ajax)?\.action$`)
func newProxy(upstream *url.URL) *httputil.ReverseProxy {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConnsPerHost = 100
transport.ResponseHeaderTimeout = 15 * time.Second
return &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetURL(upstream)
r.Out.Header.Set("Referer", upstream.String())
r.Out.Header.Del("Cookie")
},
ModifyResponse: func(resp *http.Response) error {
resp.Header.Del("Set-Cookie")
path := resp.Request.URL.Path
if (strings.HasPrefix(path, "/kor/") || strings.HasPrefix(path, "/adm/")) &&
(resp.StatusCode < 300 || resp.StatusCode == http.StatusNotModified) &&
resp.Header.Get("Cache-Control") == "" {
resp.Header.Set("Cache-Control", "public, max-age=86400")
}
return nil
},
Transport: transport,
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
if r.Context().Err() != nil {
w.WriteHeader(statusClientClosedRequest)
return
}
log.Printf("upstream error: %s %s: %v", r.Method, r.URL.Path, err)
http.Error(w, "upstream error", http.StatusBadGateway)
},
}
}
func hasParentSegment(path string) bool {
segments := strings.FieldsFunc(path, func(r rune) bool { return r == '/' || r == '\\' })
for _, segment := range segments {
name, _, _ := strings.Cut(segment, ";")
if name == ".." {
return true
}
}
return false
}
func newHandler(proxy http.Handler) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("ok"))
})
proxyAction := func(w http.ResponseWriter, r *http.Request) {
if !allowedAction.MatchString(r.PathValue("action")) {
http.NotFound(w, r)
return
}
proxy.ServeHTTP(w, r)
}
mux.HandleFunc("GET /sugang/cc/{action}", proxyAction)
mux.HandleFunc("POST /sugang/cc/{action}", proxyAction)
proxyStatic := func(w http.ResponseWriter, r *http.Request) {
if hasParentSegment(r.URL.Path) {
http.NotFound(w, r)
return
}
proxy.ServeHTTP(w, r)
}
mux.HandleFunc("GET /kor/", proxyStatic)
mux.HandleFunc("GET /adm/", proxyStatic)
return logRequests(mux)
}
func logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/healthz" {
next.ServeHTTP(w, r)
return
}
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(sw, r)
log.Printf("%s %s %d %s", r.Method, r.URL.RequestURI(), sw.status, time.Since(start).Round(time.Millisecond))
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
upstream, err := url.Parse(upstreamBase)
if err != nil {
log.Fatal(err)
}
server := &http.Server{
Addr: ":" + port,
Handler: newHandler(newProxy(upstream)),
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
log.Printf("listening on :%s, proxying %s", port, upstreamBase)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Printf("shutdown: %v", err)
}
}