-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpodder.go
63 lines (52 loc) · 1.45 KB
/
podder.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"strings"
)
func main() {
port := fmt.Sprintf(":%s", os.Getenv("PORT"))
log.Printf("Starting on port %s ....", port)
http.ListenAndServe(port, proxy())
}
func proxy() *httputil.ReverseProxy {
proxyUrl, _ := url.Parse(os.Getenv("PROXY_URL"))
proxy := httputil.NewSingleHostReverseProxy(proxyUrl)
director := proxy.Director
proxy.Director = func(req *http.Request) {
req.Header.Set("X-Proxy-Host", req.Host)
req.Host = proxyUrl.Host
req.SetBasicAuth(os.Getenv("USER"), os.Getenv("PASS"))
director(req)
}
proxy.Transport = &proxyTransport{}
return proxy
}
type proxyTransport struct{}
func (t *proxyTransport) RoundTrip(request *http.Request) (*http.Response, error) {
response, err := http.DefaultTransport.RoundTrip(request)
if response.Header.Get("Content-Type") != "audio/mpeg" {
body := new(bytes.Buffer)
body.ReadFrom(response.Body)
target := request.Host
replacement := request.Header.Get("X-Proxy-Host")
proto := request.Header.Get("X-Forwarded-Proto")
if len(proto) > 0 {
target = "http://" + target
replacement = proto + "://" + replacement
}
bod := strings.Replace(body.String(), target, replacement, -1)
buf := bytes.NewBufferString(bod)
contentLength := strconv.Itoa(buf.Len())
response.Body = ioutil.NopCloser(buf)
response.Header.Set("Content-Length", contentLength)
}
return response, err
}