/
connection.go
54 lines (39 loc) · 1.05 KB
/
connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package helper
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// ConnectDB : This is helper function to connect mongoDB
func ConnectDB() *mongo.Database {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("go_rest_api")
return collection
}
// ErrorResponse : This is error model.
type ErrorResponse struct {
StatusCode int `json:"status"`
ErrorMessage string `json:"message"`
}
// GetError : This is helper function to prepare error model.
func GetError(err error, w http.ResponseWriter) {
//log.Fatal(err.Error())
var response = ErrorResponse{
ErrorMessage: err.Error(),
StatusCode: http.StatusInternalServerError,
}
message, _ := json.Marshal(response)
w.WriteHeader(response.StatusCode)
w.Write(message)
}