Basic music streaming with go fiber
October 08, 2021
1 min
##Docker compose ทำ mongodb มาเชื่อมต่อ กับ golang
version: "3.7"services:database:image: mongo:4.4ports:- 27017:27017environment:- MONGO_INITDB_ROOT_USERNAME=root- MONGO_INITDB_ROOT_PASSWORD=password- MONGO_INITDB_DATABASE=dd_hakka- MONGO_INITDB_USERNAME=dd_hakka- MONGO_INITDB_PASSWORD=passwordvolumes:- ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh- ./db:/data/db
package mainimport ("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)}
Quick Links
Legal Stuff