This repository has been archived by the owner on Oct 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (77 loc) · 1.71 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"github.com/gorilla/mux"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
)
func main() {
upstream := os.Getenv("AS_PROXY_TO_ADDR")
bind:= os.Getenv("AS_PROXY_BIND")
log.Println("Preparing local server...")
rtr := mux.NewRouter()
rtr.HandleFunc("/_matrix/client/r0/register", func(w http.ResponseWriter, r *http.Request) {
log.Println("Register request received:", r.RequestURI)
defer dumpAndCloseStream(r.Body)
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
i := make(map[string]interface{})
err = json.Unmarshal(b, &i)
if err != nil {
log.Fatal(err)
}
if _, ok := i["type"]; !ok {
i["type"] = "m.login.application_service"
}
j, err := json.Marshal(i)
if err != nil {
log.Fatal(err)
}
r2, err := http.NewRequest(r.Method, upstream + r.RequestURI, bytes.NewBuffer(j))
if err != nil {
log.Fatal(err)
}
for k, v := range r.Header {
r2.Header.Set(k, v[0])
}
resp, err := http.DefaultClient.Do(r2)
if err != nil {
log.Fatal(err)
}
for k, v := range resp.Header {
w.Header().Set(k, v[0])
}
defer dumpAndCloseStream(resp.Body)
_, err = io.Copy(w, resp.Body)
if err != nil {
log.Fatal(err)
}
})
srv := &http.Server{Addr: bind, Handler: rtr}
stop := make(chan os.Signal)
signal.Notify(stop, os.Interrupt, os.Kill)
go func() {
defer close(stop)
<-stop
log.Println("Stopping local server...")
_ = srv.Close()
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
log.Println("Goodbye!")
}
func dumpAndCloseStream(r io.ReadCloser) {
if r == nil {
return // nothing to dump or close
}
_, _ = io.Copy(ioutil.Discard, r)
_ = r.Close()
}