42 lines
884 B
Go
42 lines
884 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"github.com/gorilla/mux"
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
)
|
||
|
|
||
|
func run() {
|
||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||
|
db, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:example@localhost:27017"))
|
||
|
if err != nil {
|
||
|
log.Fatal("Can not connect to db: ", err)
|
||
|
}
|
||
|
if err := db.Ping(ctx, nil); err != nil {
|
||
|
log.Fatal("Can not connect to db: ", err)
|
||
|
}
|
||
|
cancel()
|
||
|
//
|
||
|
defer func() {
|
||
|
if err := db.Disconnect(context.TODO()); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
}()
|
||
|
storage := MongodbStorage{db: db}
|
||
|
|
||
|
router := mux.NewRouter()
|
||
|
server := Server{
|
||
|
host: ":4000",
|
||
|
mux: router,
|
||
|
db: storage,
|
||
|
}
|
||
|
server.InitHandlers()
|
||
|
log.Println("Server starting at ", server.host)
|
||
|
log.Fatal(http.ListenAndServe(server.host, router))
|
||
|
}
|