go-mongo/main.go
2021-12-10 18:17:24 +07:00

159 lines
5.0 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"text/template"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Hero struct {
Name string `json:"name"`
Alias int64 `json:"alias"`
Signed bool `json:"signed"`
}
var database = "olshop"
var collection = "heroes"
func GetClient() *mongo.Client {
clientOptions := options.Client().ApplyURI("mongodb+srv://hasnul:hasnul@cluster0.bu9d7.gcp.mongodb.net/olshop?retryWrites=true&w=majority")
client, err := mongo.NewClient(clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.Background())
if err != nil {
log.Fatal(err)
}
return client
}
func getDB(client *mongo.Client, filter bson.M) []*Hero {
var heroes []*Hero
collection := client.Database(database).Collection(collection)
cur, err := collection.Find(context.TODO(), filter)
if err != nil {
log.Fatal("Error on Finding all the documents", err)
}
for cur.Next(context.TODO()) {
var hero Hero
err = cur.Decode(&hero)
if err != nil {
log.Fatal("Error on Decoding the document", err)
}
heroes = append(heroes, &hero)
}
return heroes
}
func insertDB(client *mongo.Client, hero Hero) interface{} {
collection := client.Database(database).Collection(collection)
insertResult, err := collection.InsertOne(context.TODO(), hero)
if err != nil {
log.Fatalln("Error on inserting new Hero", err)
}
return insertResult.InsertedID
}
func deleteDB(client *mongo.Client, filter bson.M) int64 {
collection := client.Database(database).Collection(collection)
deleteResult, err := collection.DeleteOne(context.TODO(), filter)
if err != nil {
log.Fatal("Error on deleting one Hero", err)
}
return deleteResult.DeletedCount
}
func updateDB(client *mongo.Client, updatedData bson.M, filter bson.M) int64 {
collection := client.Database(database).Collection(collection)
atualizacao := bson.D{ {Key: "$set", Value: updatedData} }
updatedResult, err := collection.UpdateOne(context.TODO(), filter, atualizacao)
if err != nil {
log.Fatal("Error on updating one Hero", err)
}
return updatedResult.ModifiedCount
}
func findDB(client *mongo.Client, filter bson.M) Hero {
var hero Hero
collection := client.Database(database).Collection(collection)
documentReturned := collection.FindOne(context.TODO(), filter)
documentReturned.Decode(&hero)
return hero
}
func main() {
c := GetClient()
err := c.Ping(context.Background(), readpref.Primary())
if err != nil {
log.Fatal("Couldn't connect to the database", err)
} else {
log.Println("Connected!")
}
http.HandleFunc("/read", func(w http.ResponseWriter, r *http.Request){
heroes := getDB(c, bson.M{})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(heroes)
})
http.HandleFunc("/insert", func(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
var id = insertDB(c, Hero{Name: uuid.New().String(), Alias: time.Now().Unix(), Signed: true})
json.NewEncoder(w).Encode(id)
})
http.HandleFunc("/update/", func(w http.ResponseWriter, r *http.Request){
p := strings.Split(r.URL.Path, "/update/")
if(p[1] != "") {
hero := findDB(c, bson.M{"name": p[1]})
log.Println(hero)
var result = updateDB(c, bson.M{"alias": time.Now().Unix()}, bson.M{"name": p[1]} )
json.NewEncoder(w).Encode(result)
}else{
json.NewEncoder(w).Encode("Use /update/name-to-update")
}
})
http.HandleFunc("/delete/", func(w http.ResponseWriter, r *http.Request){
p := strings.Split(r.URL.Path, "/delete/")
if(p[1] != "") {
var result = deleteDB(c, bson.M{"name": p[1] })
json.NewEncoder(w).Encode(result)
log.Println("Deleted. ")
}else{
json.NewEncoder(w).Encode("Use /delete/name-to-delete")
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
var view string = `<pre>
<a target="_blank" href="/read">Read</a>
<a target="_blank" href="/insert">Insert: /insert/name-to-insert</a>
<a target="_blank" href="/update">Update: /update/name-to-update</a>
<a target="_blank" href="/delete">Delete: /delete/name-to-delete</a>
</pre>`
var tmpl = template.Must(template.New("main-template").Parse(view))
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
fmt.Println("server started at localhost:8000")
http.ListenAndServe(":8000", nil)
}