|
| 1 | +export const description = |
| 2 | + 'Use the Nitric framework to easily build and deploy Go WebSocket applications for AWS, Azure or GCP' |
| 3 | + |
| 4 | +export const title_meta = |
| 5 | + 'Building your first WebSocket Application with Go and Nitric' |
| 6 | + |
| 7 | +# Building your first WebSocket Application with Nitric |
| 8 | + |
| 9 | +## What we'll be doing |
| 10 | + |
| 11 | +1. Use Nitric to create a WebSocket endpoint |
| 12 | +2. Manage WebSocket connections using a Key-Value store |
| 13 | +3. Handle WebSocket events: |
| 14 | + - Register connections on connect |
| 15 | + - Remove connections on disconnect |
| 16 | + - Broadcast messages to all connected clients |
| 17 | +4. Run locally for testing |
| 18 | +5. Deploy to a cloud of your choice |
| 19 | + |
| 20 | +## Prerequisites |
| 21 | + |
| 22 | +- [Go](https://go.dev/dl/) |
| 23 | +- The [Nitric CLI](https://nitric.io/docs/installation) |
| 24 | +- An [AWS](https://aws.amazon.com), [GCP](https://cloud.google.com), or [Azure](https://azure.microsoft.com) account (_your choice_) |
| 25 | + |
| 26 | +## Getting started |
| 27 | + |
| 28 | +We'll start by creating a new project for our WebSocket application. |
| 29 | + |
| 30 | +```bash |
| 31 | +nitric new my-websocket-app go-starter |
| 32 | +``` |
| 33 | + |
| 34 | +Next, open the project in your editor of choice. |
| 35 | + |
| 36 | +```bash |
| 37 | +cd my-websocket-app |
| 38 | +``` |
| 39 | + |
| 40 | +Make sure all dependencies are resolved: |
| 41 | + |
| 42 | +```bash |
| 43 | +go mod tidy |
| 44 | +``` |
| 45 | + |
| 46 | +The scaffolded project should have the following structure: |
| 47 | + |
| 48 | +```text |
| 49 | ++--services/ |
| 50 | +| +-- hello/ |
| 51 | +| +-- main.go |
| 52 | +| ... |
| 53 | ++--nitric.yaml |
| 54 | ++--go.mod |
| 55 | ++--go.sum |
| 56 | ++--golang.dockerfile |
| 57 | ++--.gitignore |
| 58 | ++--README.md |
| 59 | +``` |
| 60 | + |
| 61 | +You can test the project to verify everything is working as expected: |
| 62 | + |
| 63 | +```bash |
| 64 | +nitric start |
| 65 | +``` |
| 66 | + |
| 67 | +If everything is working as expected, you can now delete all files/folders in the `services/` folder. We'll create new services in this guide. |
| 68 | + |
| 69 | +## Building the WebSocket Application |
| 70 | + |
| 71 | +Let's begin by setting up the WebSocket application. First, create a new folder called `websockets` within the services directory. Inside this folder, add a file named `main.go`, and include the following code: |
| 72 | + |
| 73 | +```go |
| 74 | +package main |
| 75 | + |
| 76 | +import ( |
| 77 | + "context" |
| 78 | + "fmt" |
| 79 | + |
| 80 | + "github.com/nitrictech/go-sdk/handler" |
| 81 | + "github.com/nitrictech/go-sdk/nitric" |
| 82 | +) |
| 83 | + |
| 84 | +func main() { |
| 85 | + ws, err := nitric.NewWebsocket("public") |
| 86 | + if err != nil { |
| 87 | + fmt.Println("Error creating WebSocket:", err) |
| 88 | + return |
| 89 | + } |
| 90 | + |
| 91 | + connections, err := nitric.NewKv("connections").Allow(nitric.KvStoreGet, nitric.KvStoreSet, nitric.KvStoreDelete) |
| 92 | + if err != nil { |
| 93 | + fmt.Println("Error creating KV store:", err) |
| 94 | + return |
| 95 | + } |
| 96 | + |
| 97 | + // Add event handlers here |
| 98 | + |
| 99 | + if err := nitric.Run(); err != nil { |
| 100 | + fmt.Println("Error running Nitric service:", err) |
| 101 | + } |
| 102 | +} |
| 103 | +``` |
| 104 | + |
| 105 | +Here we're creating: |
| 106 | + |
| 107 | +- A WebSocket endpoint named `public` |
| 108 | +- A Key-Value store named `connections` to track WebSocket connections |
| 109 | + |
| 110 | +From here, let's add some features to that function that allow us to manage connections and broadcast messages. |
| 111 | + |
| 112 | +<Note> |
| 113 | + You could separate some or all of these event handlers into their own services |
| 114 | + if you prefer. For simplicity, we'll group them together in this guide. |
| 115 | +</Note> |
| 116 | + |
| 117 | +### Register connections on connect |
| 118 | + |
| 119 | +```go |
| 120 | +ws.On(handler.WebsocketConnect, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) { |
| 121 | + err := connections.Set(context.TODO(), ctx.Request.ConnectionID(), map[string]interface{}{ |
| 122 | + "connectionId": ctx.Request.ConnectionID(), |
| 123 | + }) |
| 124 | + if err != nil { |
| 125 | + return ctx, err |
| 126 | + } |
| 127 | + |
| 128 | + return next(ctx) |
| 129 | +}) |
| 130 | +``` |
| 131 | + |
| 132 | +### Remove connections on disconnect |
| 133 | + |
| 134 | +```go |
| 135 | +ws.On(handler.WebsocketDisconnect, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) { |
| 136 | + err := connections.Delete(context.TODO(), ctx.Request.ConnectionID()) |
| 137 | + if err != nil { |
| 138 | + return ctx, err |
| 139 | + } |
| 140 | + |
| 141 | + return next(ctx) |
| 142 | +}) |
| 143 | +``` |
| 144 | + |
| 145 | +### Broadcast messages to all connected clients |
| 146 | + |
| 147 | +```go |
| 148 | +ws.On(handler.WebsocketMessage, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) { |
| 149 | + connectionStream, err := connections.Keys(context.TODO()) |
| 150 | + if err != nil { |
| 151 | + return ctx, err |
| 152 | + } |
| 153 | + |
| 154 | + senderId := ctx.Request.ConnectionID() |
| 155 | + |
| 156 | + for { |
| 157 | + connectionId, err := connectionStream.Recv() |
| 158 | + if err != nil { |
| 159 | + break |
| 160 | + } |
| 161 | + |
| 162 | + if connectionId == senderId { |
| 163 | + continue |
| 164 | + } |
| 165 | + |
| 166 | + message := fmt.Sprintf("%s: %s", senderId, ctx.Request.Message()) |
| 167 | + err = ws.Send(context.TODO(), connectionId, []byte(message)) |
| 168 | + if err != nil { |
| 169 | + return ctx, err |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + return next(ctx) |
| 174 | +}) |
| 175 | +``` |
| 176 | + |
| 177 | +Do a quick `go mod tidy` to make sure all new dependencies are resolved. |
| 178 | + |
| 179 | +## Ok, let's run this thing! |
| 180 | + |
| 181 | +Now that you have your WebSocket application defined with handlers for each event, it's time to test it locally. |
| 182 | + |
| 183 | +```bash |
| 184 | +nitric start |
| 185 | +``` |
| 186 | + |
| 187 | +Once it starts, the application will be ready to accept WebSocket connections. You can use a WebSocket client like Postman or any other WebSocket tool to test the application. |
| 188 | + |
| 189 | +We will keep it running for our tests. If you want to update your services, just save them, and they'll be reloaded automatically. |
| 190 | + |
| 191 | +## Deploy to the cloud |
| 192 | + |
| 193 | +At this point, you can deploy what you've built to any of the supported cloud providers. To do this, start by setting up your credentials and any configuration for the cloud you prefer: |
| 194 | + |
| 195 | +- [AWS](/reference/providers/aws) |
| 196 | +- [Azure](/reference/providers/azure) |
| 197 | +- [GCP](/reference/providers/gcp) |
| 198 | + |
| 199 | +Next, we'll need to create a `stack`. A stack represents a deployed instance of an application, which is a key value store of resources defined in your project. You might want separate stacks for each environment, such as stacks for `dev`, `test`, and `prod`. For now, let's start by creating a `dev` stack. |
| 200 | + |
| 201 | +The `stack new` command below will create a stack named `dev` that uses the `aws` provider. |
| 202 | + |
| 203 | +```bash |
| 204 | +nitric stack new dev aws |
| 205 | +``` |
| 206 | + |
| 207 | +Continue by checking your stack file `nitric.dev.yaml` and adding in your preferred region. Let's use `us-east-1`. |
| 208 | + |
| 209 | +### AWS |
| 210 | + |
| 211 | +Note: You are responsible for staying within the limits of the free tier or any costs associated with deployment. |
| 212 | + |
| 213 | +We called our stack `dev`. Let's try deploying it with the `up` command: |
| 214 | + |
| 215 | +```bash |
| 216 | +nitric up |
| 217 | +``` |
| 218 | + |
| 219 | +When the deployment is complete, go to the relevant cloud console and you'll be able to see and interact with your WebSocket application. |
| 220 | + |
| 221 | +To tear down your application from the cloud, use the `down` command: |
| 222 | + |
| 223 | +```bash |
| 224 | +nitric down |
| 225 | +``` |
| 226 | + |
| 227 | +## Summary |
| 228 | + |
| 229 | +In this guide, we've created a serverless WebSocket application using Go and Nitric. We've demonstrated how to set up WebSocket connections, track clients using a Key-Value store, and broadcast messages to all connected clients. This application can be easily deployed to the cloud, allowing you to build scalable, real-time communication systems. |
| 230 | + |
| 231 | +For more information and advanced usage, refer to the [Nitric documentation](https://nitric.io/docs). |
0 commit comments