-
Notifications
You must be signed in to change notification settings - Fork 11
feat(go): mongo db sample #100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9261831
feat(go): mongo db sample
thomas-tacquet a61d2ee
base readme update
thomas-tacquet 22f6d59
format
thomas-tacquet 664d4ef
Apply suggestions from code review
thomas-tacquet 511123a
review
thomas-tacquet 4338afd
oui
thomas-tacquet 3ad351e
QueryEscape
thomas-tacquet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
# Mongo + Go example | ||
|
||
Example to demonstrate the possibility of connecting Serverless Functions to MongoDB. | ||
|
||
For this example, [Scaleway Console](https://console.scaleway.com/) will be used for deployment. | ||
|
||
> [!WARNING] | ||
> This is a basic sample that does not use a certificate for authentication, not recommended for production. | ||
|
||
## Requirements | ||
|
||
- MongoDB created [documentation](https://www.scaleway.com/en/docs/managed-mongodb-databases/quickstart/#how-to-create-a-database-instance) | ||
- The MongoDB instance must be public (not listening to a private network only since Serverless Functions do not support private networks yet) | ||
|
||
## Step 1 - Mongo | ||
|
||
After MongoDB creation, in the console, find the public endpoint of the database; it should look like: `<scw_database_id>.mgdb.<scw_region>.scw.cloud` | ||
|
||
Once you get the endpoint, keep it somewhere for later use. | ||
|
||
## Step 2 - Function Creation | ||
|
||
Before creating the Function, we need to package it into a zip file. | ||
|
||
> [!TIP] | ||
> It's recommended to do it via command line tools, so the following example shows how to zip this current folder: | ||
> | ||
> ```sh | ||
> cd ~/scaleway/serverless-examples/functions/go-mongo/ | ||
> zip -r go-mongo.zip * | ||
> ``` | ||
|
||
- Create a Serverless Function namespace. [Documentation](https://www.scaleway.com/en/docs/serverless-functions/how-to/create-manage-delete-functions-namespace/#creating-a-serverless-functions-namespace) | ||
- In the created namespace, create a Serverless Function. | ||
- Select the latest Go runtime. | ||
- Upload the previously created `go-mongo.zip`. | ||
- Ensure the handler is `Handle`. | ||
- Add required Secrets to the Function: | ||
|
||
| Key | Value | | ||
| --------------------- | -------------------------------------------------------------------------------------------------------------- | | ||
| MONGO_PUBLIC_ENDPOINT | (replace with required values): `<scw_database_id>.mgdb.<scw_region>.scw.cloud` | | ||
| MONGO_USER | user created during MongoDB setup | | ||
| MONGO_PASSWORD | password created during MongoDB user setup | | ||
norbjd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## Step 3 - Test | ||
|
||
Once your Serverless Function is in `ready` state, you can call it using the generated endpoint. | ||
|
||
Result should be similar to: | ||
|
||
```json | ||
{ "ID": 2911126, "Name": "RandomName2911126" } | ||
``` | ||
|
||
## Local testing | ||
|
||
For testing, you can use [Go Offline Testing](https://github.com/scaleway/serverless-functions-go). | ||
|
||
To run locally, execute: `go run cmd/main.go`. |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package main | ||
|
||
import ( | ||
scw "github.com/scaleway/serverless-examples/functions/go-mongo" | ||
"github.com/scaleway/serverless-functions-go/local" | ||
) | ||
|
||
// https://github.com/scaleway/serverless-functions-go | ||
func main() { | ||
// Replace "Handle" with your function handler name if necessary | ||
local.ServeHandler(scw.Handle, local.WithPort(8080)) | ||
} |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
module github.com/scaleway/serverless-examples/functions/go-mongo | ||
|
||
go 1.24 | ||
|
||
require ( | ||
github.com/scaleway/serverless-functions-go v0.1.2 | ||
go.mongodb.org/mongo-driver v1.17.3 | ||
) | ||
|
||
require ( | ||
github.com/golang/snappy v1.0.0 // indirect | ||
github.com/google/go-cmp v0.7.0 // indirect | ||
github.com/google/uuid v1.6.0 // indirect | ||
github.com/klauspost/compress v1.18.0 // indirect | ||
github.com/montanaflynn/stats v0.7.1 // indirect | ||
github.com/stretchr/testify v1.10.0 // indirect | ||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect | ||
github.com/xdg-go/scram v1.1.2 // indirect | ||
github.com/xdg-go/stringprep v1.0.4 // indirect | ||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect | ||
golang.org/x/crypto v0.38.0 // indirect | ||
golang.org/x/sync v0.14.0 // indirect | ||
golang.org/x/text v0.25.0 // indirect | ||
) |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= | ||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= | ||
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= | ||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= | ||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= | ||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= | ||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= | ||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= | ||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= | ||
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= | ||
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= | ||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= | ||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||
github.com/scaleway/serverless-functions-go v0.1.2 h1:UUToB+XXpLDG9l6c9c0ALhAs1jvb6rV2Lkyj2kZEYCo= | ||
github.com/scaleway/serverless-functions-go v0.1.2/go.mod h1:23Hj74DYzTsVY3QgvsM0MGnx0+0OAAabTC06BOMJE58= | ||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= | ||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= | ||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= | ||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= | ||
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= | ||
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= | ||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= | ||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= | ||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= | ||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= | ||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= | ||
go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ= | ||
go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= | ||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= | ||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= | ||
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= | ||
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= | ||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= | ||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= | ||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= | ||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= | ||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | ||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | ||
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ= | ||
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= | ||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | ||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= | ||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= | ||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= | ||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= | ||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= | ||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= | ||
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= | ||
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= | ||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= | ||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= | ||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= | ||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= | ||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= | ||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
package example | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"log/slog" | ||
"math/rand" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
|
||
"go.mongodb.org/mongo-driver/bson" | ||
"go.mongodb.org/mongo-driver/mongo" | ||
"go.mongodb.org/mongo-driver/mongo/options" | ||
) | ||
|
||
// client is a global variable that holds the MongoDB client instance. | ||
var client *mongo.Client | ||
|
||
// RandomDocument represents a document in the MongoDB collection with an ID and a Name. | ||
type RandomDocument struct { | ||
ID int `bson:"id"` | ||
Name string `bson:"name"` | ||
} | ||
|
||
// init initializes the MongoDB client connection. | ||
// It reads the MongoDB connection details from environment variables and establishes a connection. | ||
func init() { | ||
mongoPublicEndpoint := os.Getenv("MONGO_PUBLIC_ENDPOINT") | ||
if mongoPublicEndpoint == "" { | ||
panic("MONGO_PUBLIC_ENDPOINT is required") | ||
} | ||
|
||
mongoUser := os.Getenv("MONGO_USER") | ||
if mongoUser == "" { | ||
panic("MONGO_USER is required") | ||
} | ||
|
||
mongoPassword := url.QueryEscape(os.Getenv("MONGO_PASSWORD")) | ||
if mongoPassword == "" { | ||
panic("MONGO_PASSWORD is required") | ||
} | ||
|
||
// This is a basic sample that does not use certificate for authentication, not recommended for production. | ||
mongoURI := fmt.Sprintf(`mongodb+srv://%s:%s@%s/?tls=true&tlsInsecure=true`, | ||
mongoUser, | ||
mongoPassword, | ||
mongoPublicEndpoint) | ||
|
||
var err error | ||
|
||
client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI(mongoURI)) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
err = client.Ping(context.TODO(), nil) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
slog.Info("Connected to MongoDB") | ||
} | ||
|
||
// Handle is an HTTP handler function that inserts a random document into the MongoDB collection | ||
// and returns the inserted document as a JSON response. | ||
func Handle(w http.ResponseWriter, _ *http.Request) { | ||
collection := client.Database("testdb").Collection("testcollection") | ||
|
||
randomID := rand.Intn(100000000) | ||
|
||
doc := RandomDocument{ | ||
ID: randomID, | ||
Name: fmt.Sprintf("RandomName%d", randomID), | ||
} | ||
|
||
insertResult, err := collection.InsertOne(context.TODO(), doc) | ||
if err != nil { | ||
http.Error(w, "Failed to insert document", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
slog.Info("Inserted document", "id", insertResult.InsertedID) | ||
|
||
var result RandomDocument | ||
|
||
if err := collection.FindOne(context.TODO(), bson.M{"_id": insertResult.InsertedID}).Decode(&result); err != nil { | ||
http.Error(w, "Failed to find document", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
slog.Info("Found document", "name", result.Name, "id", result.ID) | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
|
||
if err := json.NewEncoder(w).Encode(result); err != nil { | ||
http.Error(w, "Failed to encode response", http.StatusInternalServerError) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.