我想运行 3 个服务:
My Go程序,它将连接到另一个容器中的MongoDB
蒙戈
蒙戈快捷酒店
这是我的docker-compose.yml:
version: "3.7"
services:
app:
image: test-go-docker
environment:
- MONGO_HST=mongo
- MONGO_PRT=27018
mongo:
image: mongo
ports:
- 27018:27017
volumes:
- /data/db
mongo-express:
image: mongo-express
ports:
- 8081:8081
如您所见,我的Mongo数据库映射到端口217018,网络名称为mongo。
我的Golang程序将通过环境变量(MONGO_HST和MONGO_PRT)获取主机名和端口。这是我的Go计划:
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"net/http"
"os"
"time"
)
type MyData struct {
Name string
Text string
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!")
}
func main() {
mongoURI := "mongodb://" + os.Getenv("MONGO_HST") + ":" + os.Getenv("MONGO_PRT") + "/"
client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
must(err)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = client.Connect(ctx)
collection := client.Database("test_db").Collection("test_collection")
data := MyData{
Name: "testing...",
Text: "Hello world",
}
_, err =collection.InsertOne(context.Background(), data)
must(err)
// Serve the page
http.HandleFunc("/", viewHandler)
err = http.ListenAndServe(":8000", nil)
must(err)
}
func must(err error) {
if err != nil {
fmt.Println("Some error...")
panic(err)
}
}
繁花不似锦
相关分类