/
connection.go
69 lines (53 loc) · 1.73 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package helper
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type clientOptions *options.ClientOptions
func clientOpts() clientOptions {
str := "mongodb://localhost:27017"
return options.Client().ApplyURI(str)
}
// ConnectDB : This is helper function to connect mongoDB
// If you want to export your function. You must to start upper case function name. Otherwise you won't see your function when you import that on other class.
func ConnectDB(dbname string, col string) *mongo.Collection {
// Set client options
/*clientOptions := clientOpts()
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}*/
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(
"mongodb+srv://jiojhoi",
))
if err != nil { log.Fatal(err) }
fmt.Println("Connected to MongoDB!")
collection := client.Database(dbname).Collection(col)
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.
// If you want to export your function. You must to start upper case function name. Otherwise you won't see your function when you import that on other class.
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)
}