github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/examples/wss/main.go (about) 1 /* 2 Copyright [2014] - [2023] The Last.Backend authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "context" 21 "fmt" 22 "io" 23 "net/http" 24 "os" 25 26 servicepb "github.com/lastbackend/toolkit/examples/wss/gen/server" 27 "github.com/lastbackend/toolkit/examples/wss/middleware" 28 "github.com/lastbackend/toolkit/pkg/runtime" 29 tk_http "github.com/lastbackend/toolkit/pkg/server/http" 30 "github.com/lastbackend/toolkit/pkg/server/http/websockets" 31 ) 32 33 func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { 34 w.Header().Set("Content-Type", "application/json") 35 w.WriteHeader(http.StatusOK) 36 if _, err := io.WriteString(w, `{"alive": true}`); err != nil { 37 fmt.Println(err) 38 } 39 } 40 41 func TestWSHandler(ctx context.Context, event websockets.Event, c *websockets.Client) error { 42 fmt.Println("Event:", event.Type, string(event.Payload)) 43 fmt.Println("Context:", ctx.Value("test-data")) 44 return c.WriteMessage(websockets.TextMessage, event.Payload) 45 } 46 47 func main() { 48 49 // define service with name and options 50 app, err := servicepb.NewRouterService("wss", 51 runtime.WithVersion("0.1.0"), 52 runtime.WithDescription("Example router microservice"), 53 runtime.WithEnvPrefix("WSS"), 54 ) 55 if err != nil { 56 fmt.Println(err) 57 } 58 59 // Logger settings 60 app.Log().Info("Run microservice") 61 62 // Add middleware 63 app.Server().HTTP().SetMiddleware(middleware.RegisterExampleMiddleware) 64 app.Server().HTTP().SetMiddleware(middleware.RegisterRequestID) 65 66 // set middleware as global middleware 67 app.Server().HTTP().UseMiddleware("request_id") 68 app.Server().HTTP().Subscribe("event:name", TestWSHandler) 69 70 // add handler to default http server 71 app.Server().HTTP(). 72 AddHandler(http.MethodGet, "/health", HealthCheckHandler, tk_http.WithMiddleware("example")) 73 74 // Service run 75 if err := app.Start(context.Background()); err != nil { 76 app.Log().Errorf("could not run the service %v", err) 77 os.Exit(1) 78 return 79 } 80 81 app.Log().Info("graceful stop") 82 }