Skip to content

Commit aefc425

Browse files
committed
go sources first
1 parent c674483 commit aefc425

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

go.mod

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module github.com/setlog/go-mongo-atlas
2+
3+
go 1.13
4+
5+
require (
6+
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
7+
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
8+
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
9+
gopkg.in/yaml.v2 v2.3.0 // indirect
10+
)

main.go

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package main
2+
3+
import (
4+
"crypto/tls"
5+
"io/ioutil"
6+
"net"
7+
"net/http"
8+
9+
mgo "gopkg.in/mgo.v2"
10+
"gopkg.in/mgo.v2/bson"
11+
)
12+
13+
var mongoConn *mgo.Session
14+
15+
type MyEntity struct {
16+
Data []byte `json:"data" bson:"data"`
17+
}
18+
19+
func main() {
20+
var err error
21+
mongoConn, err = createConnection()
22+
if err != nil {
23+
panic(err)
24+
}
25+
26+
http.HandleFunc("/save", post)
27+
http.HandleFunc("/read", get)
28+
29+
if err := http.ListenAndServe(":8080", nil); err != nil {
30+
panic(err)
31+
}
32+
}
33+
34+
func createConnection() (*mgo.Session, error) {
35+
dialInfo := mgo.DialInfo{
36+
Addrs: []string{"abc-shard-00-00.gcp.mongodb.net:27017", "abc-shard-00-01.gcp.mongodb.net:27017", "abc-shard-00-02.gcp.mongodb.net:27017"},
37+
Username: "MongoUser",
38+
Password: "YourVerySecurePassword",
39+
}
40+
tlsConfig := &tls.Config{}
41+
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
42+
conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
43+
return conn, err
44+
}
45+
return mgo.DialWithInfo(&dialInfo)
46+
}
47+
48+
func post(w http.ResponseWriter, req *http.Request) {
49+
payload, err := ioutil.ReadAll(req.Body)
50+
if err != nil {
51+
panic(err)
52+
}
53+
54+
session := mongoConn.Copy()
55+
defer session.Close()
56+
57+
entity := MyEntity{Data: payload}
58+
err = session.DB("test").C("data").Insert(entity)
59+
if err != nil {
60+
panic(err)
61+
}
62+
}
63+
64+
func get(w http.ResponseWriter, req *http.Request) {
65+
session := mongoConn.Copy()
66+
defer session.Close()
67+
68+
entity := MyEntity{}
69+
err := session.DB("test").C("data").Find(bson.M{}).One(&entity)
70+
if err != nil {
71+
panic(err)
72+
}
73+
74+
w.Write(entity.Data)
75+
w.Write([]byte{10})
76+
}

0 commit comments

Comments
 (0)