protoServer.go (1456B)
1 package protobufS 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "github.com/Nordgedanken/MatrixProtoBuf/jsonTypes" 7 pb "github.com/Nordgedanken/MatrixProtoBuf/matrixProtos" 8 "github.com/golang/protobuf/proto" 9 "io/ioutil" 10 "log" 11 "net/http" 12 "os" 13 ) 14 15 func StartProtoServer() { 16 log.Println("Started ProtoBuf Proxy") 17 18 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 19 w.WriteHeader(http.StatusBadRequest) 20 }) 21 22 http.HandleFunc("/versions", func(w http.ResponseWriter, r *http.Request) { 23 var versionRequest pb.VersionRequest 24 var hsVersions jsonTypes.HSVersions 25 26 req, err := ioutil.ReadAll(r.Body) 27 28 if err := proto.Unmarshal(req, &versionRequest); err != nil { 29 fmt.Println(err) 30 } 31 32 reqresp, err := http.Get("https://" + versionRequest.Address + "/_matrix/client/versions") 33 if err != nil { 34 panic(err) 35 } 36 defer reqresp.Body.Close() 37 body, err := ioutil.ReadAll(reqresp.Body) 38 39 if err = json.Unmarshal(body, &hsVersions); err != nil { 40 fmt.Println(err) 41 } 42 43 resp := &pb.VersionsResponse{ 44 Versions: []*pb.Version{}, 45 } 46 47 for _, k := range hsVersions.Versions { 48 resp.Versions = append(resp.Versions, &pb.Version{Version: k}) 49 } 50 51 out, err := proto.Marshal(resp) 52 checkError(err) 53 54 w.WriteHeader(http.StatusOK) 55 _, err = w.Write(out) 56 checkError(err) 57 }) 58 http.ListenAndServe(":3000", nil) 59 } 60 61 func checkError(err error) { 62 if err != nil { 63 fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 64 os.Exit(1) 65 } 66 }