-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_middleware.go
79 lines (65 loc) 路 1.97 KB
/
server_middleware.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
package web
import (
"io"
"log"
"net/http"
"golang.org/x/crypto/ssh"
)
type RouteMiddleware func(http.HandlerFunc) http.HandlerFunc
func MiddlewareLogRequest(logger *log.Logger) RouteMiddleware {
return func(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger.Println(r.Method, r.URL.Path, r.RemoteAddr, r.UserAgent())
h(w, r)
}
}
}
var DefaultRequestBodySize = int64(1024)
func MiddlewareLimitRequestBody(numBytes int64) RouteMiddleware {
return func(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, numBytes)
h(w, r)
}
}
}
func MiddlewareHeader(headerKey, headerValue string) RouteMiddleware {
return func(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(headerKey, headerValue)
h(w, r)
}
}
}
func MiddlewareHSTS() RouteMiddleware {
return MiddlewareHeader("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
}
func MiddlewareContentType(contentType string) RouteMiddleware {
return MiddlewareHeader("Content-Type", contentType)
}
func MiddlewareContentTypeUTF8(contentType string) RouteMiddleware {
return MiddlewareHeader("Content-Type", contentType+"; charset=UTF-8")
}
func MiddlewareContentTypeJSON() RouteMiddleware {
return MiddlewareContentTypeUTF8("application/json")
}
func MiddlewareSSHProxy(sshAddr string, cfg *ssh.ClientConfig, remoteAddr string) RouteMiddleware {
return func(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Establish connection with SSH server
conn, err := ssh.Dial("tcp", sshAddr, cfg)
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
// Establish connection with remote server
remote, err := conn.Dial("tcp", remoteAddr)
if err != nil {
log.Fatalln(err)
}
defer remote.Close()
io.Copy(remote, r.Body)
h(w, r)
}
}
}