Websockets Golang Example

0

I am using serverless framework to set up an AWS API Gateway websocket which calls a lambda function written in Go. Right now the handler only logs a message. I can connect to the websocket, and I can see the message is logged in Cloudwatch when I send a message through the socket, but I always get an error message that looks like

{
  "message": "Internal server error",
  "connectionId": "eU3C1cE7CYcCJPw=",
  "requestId": "eU3EQFX0iYcFysQ="
}

There are no errors logged for the lambda in Cloudwatch. The AWS API Gateway config looks good to me. I'm at a loss trying to think of what could cause this. Are there any examples of what a websocket handler in go should look like?

My main.go:

package main

import (
	"fmt"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func Handler(request events.APIGatewayWebsocketProxyRequest) {
	fmt.Println("default function ran")
}

func main() {
	lambda.Start(Handler)
}

Probably not super relevant but the serverless.yaml config:

functions:
  websocket-default:
    handler: bin/ws
    events:
      - websocket:
          route: $default

The payload I'm sending:

{
  "action": "whatever",
  "data":  "{whatever}"
}

This is just a copy of my SO post but thought it might fit better here.

NateN
asked 5 years ago1045 views
2 Answers
0

This method signature works. Would love some more docs/examples using golang. I have yet to successfully send a message through the socket.

type Response events.APIGatewayProxyResponse

func Handler(context context.Context, request events.APIGatewayWebsocketProxyRequest) (Response, error) 
NateN
answered 5 years ago
0

Hey NateN, not sure if you've figured this out, but I think I have a working solution for now?

I have one struct that I unmarshal the request body to EVERY TIME, no matter what the websocket action is (aside from connect/diconnect)

type WebSocketRequest struct {
	Action string          `json:"action"`
	Data   json.RawMessage `json:"data"`
}

webSocketRequest := &models.WebSocketRequest{}
if err := json.Unmarshal([]byte(request.Body), webSocketRequest); err != nil {
	return payloads.GenerateErrorResponse(500, err), nil
}

Then for the sendMessage lambda from the example they have, I use this request struct

type sendMessageRequest struct {
	Message string `json:"message"`
}

sendMessageRequest := &sendMessageRequest{}
if err := json.Unmarshal(webSocketRequest.Data, sendMessageRequest); err != nil {
	return payloads.GenerateErrorResponse(500, err), nil
}

And here is my test message
{"action":"sendmessage","data":{"message":"sending a ws message to you! <3"}}

Hope this helps

AustinK
answered 5 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions