41 lines
878 B
Go
41 lines
878 B
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
var mongoClient *mongo.Client
|
|
|
|
func init() {
|
|
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
|
|
opts := options.Client().ApplyURI("mongodb://localhost:27017").SetServerAPIOptions(serverAPI)
|
|
client, err := mongo.Connect(context.TODO(), opts)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
mongoClient = client
|
|
|
|
if err := mongoClient.Ping(context.TODO(), nil); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func getAllMessages() []Message {
|
|
collection := mongoClient.Database("chat").Collection("messages")
|
|
cursor, err := collection.Find(context.TODO(), bson.D{})
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
|
|
var Messages []Message
|
|
if err = cursor.All(context.TODO(), &Messages); err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
return Messages
|
|
}
|