Last active
January 26, 2020 14:40
-
-
Save praveen001/a70ba39765ae2d0f96e88e511199f10a to your computer and use it in GitHub Desktop.
Serverless WebSockets with API Gateway and Golang Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Connect will receive the $connect request | |
// It will handle the authorization also | |
func Connect(request APIGatewayWebsocketProxyRequest) (interface{}, error) { | |
if request.RequestContext.Authorizer == nil { | |
return Authorizer(request) | |
} | |
id := request.RequestContext.Authorizer.(map[string]interface{})["cognito:username"].(string) | |
connectionID := request.RequestContext.ConnectionID | |
StoreSocket(id, connectionID) | |
return events.APIGatewayProxyResponse{ | |
StatusCode: 200, | |
}, nil | |
} | |
// StoreSocket will store the id,connectionid map in dynamodb | |
func StoreSocket(id, connectionID string) error { | |
m := models.UserSocket{ | |
ID: id, | |
ConnectionID: connectionID, | |
} | |
av, err := dynamodbattribute.MarshalMap(m) | |
if err != nil { | |
log.Fatalln("Unable to marshal user socket map", err.Error()) | |
} | |
input := &dynamodb.PutItemInput{ | |
TableName: aws.String("go-ws-demo-sockets"), | |
Item: av, | |
} | |
sess := GetSession() | |
db := dynamodb.New(sess) | |
_, err = db.PutItem(input) | |
if err != nil { | |
log.Fatal("INSERT ERROR", err.Error()) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment