open-match.dev/open-match@v1.8.1/examples/demo/demo.go (about) 1 // Copyright 2019 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package demo contains the core startup code for running a demo. 16 package demo 17 18 import ( 19 "bytes" 20 "context" 21 "encoding/json" 22 "fmt" 23 "log" 24 "net/http" 25 26 "golang.org/x/net/websocket" 27 "open-match.dev/open-match/examples/demo/bytesub" 28 "open-match.dev/open-match/examples/demo/components" 29 "open-match.dev/open-match/examples/demo/updater" 30 "open-match.dev/open-match/internal/telemetry" 31 ) 32 33 // Run starts the provided components, and hosts a webserver for observing the 34 // output of those components. 35 func Run(comps map[string]func(*components.DemoShared)) { 36 log.Print("Initializing Server") 37 38 fileServe := http.FileServer(http.Dir("/app/static")) 39 http.Handle("/static/", http.StripPrefix("/static/", fileServe)) 40 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 41 if r.URL.Path != "/" { 42 http.NotFound(w, r) 43 return 44 } 45 fileServe.ServeHTTP(w, r) 46 }) 47 48 http.Handle(telemetry.HealthCheckEndpoint, telemetry.NewAlwaysReadyHealthCheck()) 49 50 bs := bytesub.New() 51 u := updater.New(context.Background(), func(b []byte) { 52 var out bytes.Buffer 53 err := json.Indent(&out, b, "", " ") 54 if err == nil { 55 bs.AnnounceLatest(out.Bytes()) 56 } else { 57 bs.AnnounceLatest(b) 58 } 59 }) 60 61 http.Handle("/connect", websocket.Handler(func(ws *websocket.Conn) { 62 bs.Subscribe(ws.Request().Context(), ws) 63 })) 64 65 log.Print("Starting Server") 66 67 for name, f := range comps { 68 go f(&components.DemoShared{ 69 Ctx: context.Background(), 70 Update: u.ForField(name), 71 }) 72 } 73 74 address := fmt.Sprintf(":%d", 51507) 75 err := http.ListenAndServe(address, nil) 76 log.Printf("HTTP server closed: %s", err.Error()) 77 }