/
redirector.go
47 lines (44 loc) · 1.18 KB
/
redirector.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
package httpsredirector
import (
"net"
"net/http"
"strconv"
"time"
"github.com/prasannavl/go-gluons/http/handlerutils"
"github.com/prasannavl/go-gluons/http/httpservice"
"github.com/prasannavl/go-gluons/log"
)
func Create(listenAddr string, targetAddr string) httpservice.Service {
hostAddr, err := net.ResolveTCPAddr("tcp", targetAddr)
if err != nil {
panic(err)
}
l, err := net.Listen("tcp", listenAddr)
if err != nil {
panic(err)
}
log.Infof("https-redirector endpoint: %s", l.Addr())
port := strconv.Itoa(hostAddr.Port)
shouldIncludePort := true
if hostAddr.Port == 443 {
shouldIncludePort = false
}
f := func(w http.ResponseWriter, r *http.Request) {
finalAddr := "https://" + r.Host
if shouldIncludePort {
finalAddr += ":" + port
}
finalAddr += r.RequestURI
w.Header().Set("connection", "close")
handlerutils.UnsafeRedirect(w, r, finalAddr, http.StatusPermanentRedirect)
}
server := &http.Server{
Handler: http.HandlerFunc(f),
IdleTimeout: 1 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 2 * time.Second,
ErrorLog: nil,
MaxHeaderBytes: 1 << 12, // 4kb
}
return httpservice.New("https-redirector", server, l)
}