forked from a-h/jwtproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrewritehandler.go
37 lines (33 loc) · 1 KB
/
rewritehandler.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
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
)
// RewriteHandler takes the input URL and strips the prefix from it.
type RewriteHandler struct {
PrefixToRemove string
Next http.Handler
}
// NewRewriteHandler creates a handler which strips the prefix from an incoming URL.
func NewRewriteHandler(prefixToRemove string, next http.Handler) RewriteHandler {
return RewriteHandler{
PrefixToRemove: prefixToRemove,
Next: next,
}
}
func (h RewriteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
originalURL := r.URL.String()
trimmedURL := strings.TrimPrefix(originalURL, h.PrefixToRemove)
if !strings.HasPrefix(trimmedURL, "/") {
trimmedURL = "/" + trimmedURL
}
updatedURL, err := url.Parse(trimmedURL)
if err != nil {
http.Error(w, fmt.Sprintf("Error trimming prefix '%v' from '%v', could not parse resulting URL of '%v'", h.PrefixToRemove, originalURL, trimmedURL), http.StatusInternalServerError)
return
}
r.URL = updatedURL
h.Next.ServeHTTP(w, r)
}