-
Notifications
You must be signed in to change notification settings - Fork 6
/
handler.go
141 lines (126 loc) · 3.85 KB
/
handler.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
138
139
140
141
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Originally written by Changkun Ou <changkun.de> at
// changkun.de/s/redir, adopted by Mai Yang <maiyang.me>.
package main
import (
"context"
"fmt"
"html/template"
"log"
"net"
"net/http"
"strings"
"golang.design/x/redir/internal/model"
)
type server struct {
db *model.Store
cache *lru
}
var (
xTmpl *template.Template
statsTmpl *template.Template
)
func newServer(ctx context.Context) *server {
xTmpl = template.Must(template.ParseFiles("public/x.html"))
statsTmpl = template.Must(template.ParseFiles("public/stats.html"))
db, err := model.NewDB(conf.Store)
if err != nil {
log.Fatalf("cannot establish connection to database: %v", err)
}
return &server{
db: db,
cache: newLRU(true),
}
}
func (s *server) close() {
log.Println(s.db.Close())
}
func (s *server) registerHandler() {
l := logging()
// short redirector
http.Handle(conf.S.Prefix, l(s.shortHandler()))
// repo redirector
http.Handle(conf.X.Prefix, l(s.xHandler()))
}
func logging() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
log.Println(readIP(r), r.Method, r.URL.Path)
}()
next.ServeHTTP(w, r)
})
}
}
// readIP implements a best effort approach to return the real client IP,
// it parses X-Real-IP and X-Forwarded-For in order to work properly with
// reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before
// X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
//
// This implementation is derived from gin-gonic/gin.
func readIP(r *http.Request) string {
clientIP := r.Header.Get("X-Forwarded-For")
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
if clientIP == "" {
clientIP = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
}
if clientIP != "" {
return clientIP
}
if addr := r.Header.Get("X-Appengine-Remote-Addr"); addr != "" {
return addr
}
ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
if err != nil {
return "unknown" // use unknown to guarantee non empty string
}
return ip
}
// xHandler redirect returns an HTTP handler that redirects requests for
// the tree rooted at importPath to pkg.go.dev pages for those import paths.
// The redirections include headers directing `go get.` to satisfy the
// imports by checking out code from repoPath using the configured VCS.
func (s *server) xHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
importPath := strings.TrimSuffix(req.Host+conf.X.Prefix, "/")
path := strings.TrimSuffix(req.Host+req.URL.Path, "/")
var importRoot, repoRoot, suffix string
if path == importPath {
http.Redirect(w, req, conf.X.GoDocHost+importPath, http.StatusFound)
return
}
elem := path[len(importPath)+1:]
if i := strings.Index(elem, "/"); i >= 0 {
elem, suffix = elem[:i], elem[i:]
}
importRoot = importPath + "/" + elem
repoRoot = conf.X.RepoPath + "/" + elem
// Handling 'git clone https://golang.design/x/repo'.
if suffix == "/info/refs" && strings.HasPrefix(req.URL.Query().Get("service"), "git-") && elem != "" {
http.Redirect(w, req, fmt.Sprintf("%s/info/refs?%s", repoRoot, req.URL.RawQuery), http.StatusFound)
return
}
d := &struct {
ImportRoot string
VCS string
VCSRoot string
Suffix string
GoogleAnalytics string
}{
ImportRoot: importRoot,
VCS: conf.X.VCS,
VCSRoot: repoRoot,
Suffix: suffix,
GoogleAnalytics: conf.GoogleAnalytics,
}
w.Header().Set("Cache-Control", "public, max-age=300")
err := xTmpl.Execute(w, d)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
})
}