Skip to content

Instantly share code, notes, and snippets.

@praveen001
Last active May 7, 2023 04:08
Show Gist options
  • Save praveen001/a5598e3584ad278648141d8c2f9441c7 to your computer and use it in GitHub Desktop.
Save praveen001/a5598e3584ad278648141d8c2f9441c7 to your computer and use it in GitHub Desktop.
Serverless WebSockets with API Gateway and Golang Lambda
type MessageAction struct {
Type string `json:"type"`
Payload MessagePayload `json:"payload"`
}
// MessagePayload ..
type MessagePayload struct {
Message MessageWithInfo `json:"message"`
}
// MessageWithInfo ..
type MessageWithInfo struct {
To string `json:"to"`
From string `json:"from"`
Message interface{} `json:"message"`
}
// Default ..
func Default(request APIGatewayWebsocketProxyRequest) (interface{}, error) {
b := MessageAction{}
if err := json.NewDecoder(strings.NewReader(request.Body)).Decode(&b); err != nil {
log.Println("Unable to decode body", err.Error())
}
data, _ := json.Marshal(b)
sess := GetSession()
db := dynamodb.New(sess)
queryInput := &dynamodb.QueryInput{
TableName: aws.String("go-ws-demo-sockets"),
ExpressionAttributeNames: map[string]*string{
"#id": aws.String("id"),
},
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":id": &dynamodb.AttributeValue{
S: aws.String(b.Payload.Message.To),
},
},
KeyConditionExpression: aws.String("#id=:id"),
}
output, err := db.Query(queryInput)
if err != nil {
log.Println("Unable to find connection ID", err.Error())
return nil, err
}
userSocks := make([]models.UserSocket, *output.Count)
dynamodbattribute.UnmarshalListOfMaps(output.Items, &userSocks)
for _, userSock := range userSocks {
input := &apigatewaymanagementapi.PostToConnectionInput{
ConnectionId: aws.String(userSock.ConnectionID),
Data: data,
}
apigateway := apigatewaymanagementapi.New(sess, aws.NewConfig().WithEndpoint("21gooh1x39.execute-api.us-east-1.amazonaws.com/go-websocket-demo"))
_, err = apigateway.PostToConnection(input)
if err != nil {
log.Println("ERROR", err.Error())
}
}
return events.APIGatewayProxyResponse{
StatusCode: 200,
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment