HomeArtTechHackBlockchain

Docker compose ทำ mongodb มาเชื่อมต่อ กับ golang

By Khomkrid Lerdprasert
Published in Technology
March 05, 2022
1 min read
Docker compose ทำ mongodb มาเชื่อมต่อ กับ golang

##Docker compose ทำ mongodb มาเชื่อมต่อ กับ golang

version: "3.7"
services:
database:
image: mongo:4.4
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=password
- MONGO_INITDB_DATABASE=dd_hakka
- MONGO_INITDB_USERNAME=dd_hakka
- MONGO_INITDB_PASSWORD=password
volumes:
- ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh
- ./db:/data/db
package main
import (
"context"
"log"
"time"
"github.com/aofiee/mongodb/handler"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type (
Podcast struct {
PodcastName string `bson:"podcast_name"`
}
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://dd_hakka:password@localhost:27017/dd_hakka"))
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
db := client.Database("dd_hakka")
log.Println(`Connected to db_hakka`, db)
podcastsCollection := db.Collection("podcasts")
log.Println(`Created collection podcasts`, podcastsCollection)
podcast := Podcast{
PodcastName: "The Go Programming Language",
}
log.Println(`Inserting podcast`, podcast)
podcastResult, err := podcastsCollection.InsertOne(ctx, podcast)
if err != nil {
log.Println("Error inserting podcast: ", err)
}
log.Println("Inserted podcast with ID: ", podcastResult.InsertedID)
}

Tags

#docker#golang

Share

Previous Article
บันทึก การทำ Firebase Messaging ด้วย Golang และ Config ให้ใช้งานบน iOS
Khomkrid Lerdprasert

Khomkrid Lerdprasert

Full Stack Life

Related Posts

Basic music streaming with go fiber
October 08, 2021
1 min
© 2024, All Rights Reserved.
Powered By

Quick Links

Author

Social Media