func main()

in golang/go-guestbook/src/backend/main.go [30:66]


func main() {
	ctx := context.Background()

	// PORT environment variable is set in guestbook-backend.deployment.yaml.
	port := os.Getenv("PORT")
	if port == "" {
		log.Fatal("PORT environment variable not specified")
	}
	// GUESTBOOK_DB_ADDR environment variable is set in guestbook-backend.deployment.yaml.
	dbAddr := os.Getenv("GUESTBOOK_DB_ADDR")
	if dbAddr == "" {
		log.Fatal("GUESTBOOK_DB_ADDR environment variable not specified")
	}

	mongoURI := "mongodb://" + dbAddr
	connCtx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()
	dbConn, err := mongo.Connect(connCtx, options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatalf("failed to initialize connection to mongodb: %+v", err)
	}
	if err := dbConn.Ping(connCtx, readpref.Primary()); err != nil {
		log.Fatalf("ping to mongodb failed: %+v", err)
	}

	gs := &guestbookServer{
		db: &mongodb{
			conn: dbConn,
		},
	}

	log.Printf("backend server listening on port %s", port)
	http.Handle("/messages", gs)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}