From fa863cbd121be3acb9e83cbf6acb1522bee85419 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 10:03:40 +0100 Subject: [PATCH 01/10] update 04.03.24 --- .idea/vcs.xml | 6 ++ docker-compose.yaml | 6 +- main.go | 223 ++++++++++++++++++++++++++++++++++++++------ util/structs.go | 25 +++++ util/util.go | 36 +++++++ 5 files changed, 267 insertions(+), 29 deletions(-) create mode 100644 .idea/vcs.xml create mode 100644 util/structs.go create mode 100644 util/util.go diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index 5db86a4..5af35ea 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -9,7 +9,7 @@ services: - 27017:27017 environment: MONGO_INITDB_ROOT_USERNAME: root - MONGO_INITDB_ROOT_PASSWORD: example + MONGO_INITDB_ROOT_PASSWORD: root12345 mongo-express: image: mongo-express @@ -18,5 +18,5 @@ services: - 8081:8081 environment: ME_CONFIG_MONGODB_ADMINUSERNAME: root - ME_CONFIG_MONGODB_ADMINPASSWORD: example - ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/ + ME_CONFIG_MONGODB_ADMINPASSWORD: root12345 + ME_CONFIG_MONGODB_URL: mongodb://root:root12345@mongo:27017/ diff --git a/main.go b/main.go index e968a28..28ea074 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,8 @@ package main import ( "context" "encoding/json" + "fmt" + "gibb165lb2/util" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" @@ -16,21 +18,10 @@ import ( var client *mongo.Client -type Person struct { - ID primitive.ObjectID `bson:"_id,omitempty"` - Name string `bson:"name"` -} +// func to insert 10 random persons with real names into the database and create 30 random debts for them -type Debt struct { - ID primitive.ObjectID `bson:"_id,omitempty"` - PersonID primitive.ObjectID `bson:"fk_pid"` - Amount int `bson:"amount"` - Description string `bson:"description,omitempty"` - Datetime time.Time `bson:"datetime"` -} - -func getDebtsForPerson(client *mongo.Client, personID string) ([]Debt, error) { - var results []Debt +func getDebtsForPerson(client *mongo.Client, personID string) ([]util.Debt, error) { + var results []util.Debt ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() @@ -54,7 +45,7 @@ func getDebtsForPerson(client *mongo.Client, personID string) ([]Debt, error) { // Durchlaufen des Cursors und Hinzufügen der Ergebnisse zur results-Slice for cursor.Next(ctx) { - var debt Debt + var debt util.Debt if err := cursor.Decode(&debt); err != nil { return nil, err } @@ -72,18 +63,26 @@ func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var err error - client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:example@localhost:27017")) + client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:root12345@localhost:27017")) if err != nil { panic(err) } - + //util.InsertRandomData(client) // Router initialisieren r := mux.NewRouter() r.HandleFunc("/persons", createPerson).Methods("POST") r.HandleFunc("/persons/{id}", getPerson).Methods("GET") r.HandleFunc("/persons", getAllPersons).Methods("GET") + r.HandleFunc("/personsWithDebts", getPersonsWithDebts).Methods("GET") r.HandleFunc("/persons/{id}", updatePerson).Methods("PUT") r.HandleFunc("/persons/{id}", deletePerson).Methods("DELETE") + r.HandleFunc("/persons/{id}/debts", getDebts).Methods("GET") + r.HandleFunc("/persons/{id}/debts", createDebt).Methods("POST") + r.HandleFunc("/debts/{id}", deleteDebt).Methods("DELETE") + r.HandleFunc("/debts", getAllDebts).Methods("GET") + r.HandleFunc("/debts/{id}", getDebt).Methods("GET") + r.HandleFunc("/debts/{id}", updateDebt).Methods("PUT") + err = http.ListenAndServe(":3333", r) if err != nil { log.Fatal(err) @@ -92,7 +91,7 @@ func main() { func createPerson(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - var person Person + var person util.Person json.NewDecoder(r.Body).Decode(&person) collection := client.Database("debtlist").Collection("persons") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -108,15 +107,22 @@ func createPerson(w http.ResponseWriter, r *http.Request) { } func updatePerson(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - var person Person + var person util.Person + vars := mux.Vars(r) + personID := vars["id"] + person.ID, _ = primitive.ObjectIDFromHex(personID) json.NewDecoder(r.Body).Decode(&person) + fmt.Println(person) + collection := client.Database("debtlist").Collection("persons") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() filter := bson.M{"_id": person.ID} update := bson.M{ "$set": bson.M{ - "name": person.Name, + "name": person.Name, + "age": person.Age, + "email": person.Email, }, } result, err := collection.UpdateOne(ctx, filter, update) @@ -130,12 +136,13 @@ func updatePerson(w http.ResponseWriter, r *http.Request) { } func deletePerson(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - var person Person - json.NewDecoder(r.Body).Decode(&person) + vars := mux.Vars(r) + personID := vars["id"] collection := client.Database("debtlist").Collection("persons") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - filter := bson.M{"_id": person.ID} + newPersonID, err := primitive.ObjectIDFromHex(personID) + filter := bson.M{"_id": newPersonID} result, err := collection.DeleteOne(ctx, filter) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -148,7 +155,7 @@ func getPerson(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) personID := vars["id"] w.Header().Set("Content-Type", "application/json") - var person Person + var person util.Person collection := client.Database("debtlist").Collection("persons") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -164,7 +171,7 @@ func getPerson(w http.ResponseWriter, r *http.Request) { } func getAllPersons(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - var persons []Person + var persons []util.Person collection := client.Database("debtlist").Collection("persons") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -176,7 +183,7 @@ func getAllPersons(w http.ResponseWriter, r *http.Request) { } defer cursor.Close(ctx) for cursor.Next(ctx) { - var person Person + var person util.Person cursor.Decode(&person) persons = append(persons, person) } @@ -187,3 +194,167 @@ func getAllPersons(w http.ResponseWriter, r *http.Request) { } json.NewEncoder(w).Encode(persons) } + +func getDebts(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + personID := vars["id"] + w.Header().Set("Content-Type", "application/json") + debts, err := getDebtsForPerson(client, personID) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(debts) +} + +func createDebt(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + personID := vars["id"] + json.NewDecoder(r.Body).Decode(&debt) + debt.PersonID, _ = primitive.ObjectIDFromHex(personID) + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := collection.InsertOne(ctx, debt) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} + +func deleteDebt(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + debtId := vars["id"] + json.NewDecoder(r.Body).Decode(&debt) + debt.ID, _ = primitive.ObjectIDFromHex(debtId) + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + filter := bson.M{"_id": debt.ID} + result, err := collection.DeleteOne(ctx, filter) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} + +func getAllDebts(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var debts []util.Debt + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cursor, err := collection.Find(ctx, bson.M{}) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + defer cursor.Close(ctx) + for cursor.Next(ctx) { + var debt util.Debt + cursor.Decode(&debt) + debts = append(debts, debt) + } + if err := cursor.Err(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(debts) +} + +// eine route welche alle personen zurückgibt welche ein array aus debts haben. +func getPersonsWithDebts(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var personsWithDebts []util.PersonWithDebts + var persons []util.Person + collection := client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cursor, err := collection.Find(ctx, bson.M{}) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + defer cursor.Close(ctx) + for cursor.Next(ctx) { + var person util.Person + cursor.Decode(&person) + persons = append(persons, person) + } + if err := cursor.Err(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + for _, person := range persons { + debts, err := getDebtsForPerson(client, person.ID.Hex()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + personsWithDebts = append(personsWithDebts, util.PersonWithDebts{Person: person, Debts: debts}) + } + json.NewEncoder(w).Encode(personsWithDebts) +} + +// neue route welche eine einzelne debt zurückgibt +func getDebt(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + debtID := vars["id"] + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + did, err := primitive.ObjectIDFromHex(debtID) + filter := bson.M{"_id": did} + err = collection.FindOne(ctx, filter).Decode(&debt) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(debt) +} + +// neue route welche eine einzelne debt aktualisiert +func updateDebt(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + vars := mux.Vars(r) + debtID := vars["id"] + debt.ID, _ = primitive.ObjectIDFromHex(debtID) + json.NewDecoder(r.Body).Decode(&debt) + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + filter := bson.M{"_id": debt.ID} + update := bson.M{ + "$set": bson.M{ + "fk_pid": debt.PersonID, + "amount": debt.Amount, + "description": debt.Description, + "datetime": debt.Datetime, + }, + } + result, err := collection.UpdateOne(ctx, filter, update) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} diff --git a/util/structs.go b/util/structs.go new file mode 100644 index 0000000..94ebfd0 --- /dev/null +++ b/util/structs.go @@ -0,0 +1,25 @@ +package util + +import ( + "go.mongodb.org/mongo-driver/bson/primitive" + "time" +) + +type Person struct { + ID primitive.ObjectID `bson:"_id,omitempty"` + Name string `bson:"name"` + Age int `bson:"age,omitempty" json:"age,omitempty"` + Email string `bson:"email,omitempty" json:"email,omitempty"` +} + +type Debt struct { + ID primitive.ObjectID `bson:"_id,omitempty"` + PersonID primitive.ObjectID `bson:"fk_pid"` + Amount int `bson:"amount"` + Description string `bson:"description,omitempty"` + Datetime time.Time `bson:"datetime"` +} +type PersonWithDebts struct { + Person Person `json:"person"` + Debts []Debt `json:"debts"` +} diff --git a/util/util.go b/util/util.go new file mode 100644 index 0000000..3e15609 --- /dev/null +++ b/util/util.go @@ -0,0 +1,36 @@ +package util + +import ( + "context" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "log" + "time" +) + +func InsertRandomData(client *mongo.Client) { + persons := []string{"Max", "Moritz", "Hans", "Peter", "Paul", "Klaus", "Karl", "Kai", "Kurt", "Karl-Heinz"} + debts := []Debt{} + for i := 0; i < 10; i++ { + person := Person{Name: persons[i]} + collection := client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := collection.InsertOne(ctx, person) + if err != nil { + log.Fatal(err) + } + for j := 0; j < 3; j++ { + debts = append(debts, Debt{PersonID: result.InsertedID.(primitive.ObjectID), Amount: j * 100, Description: "Test", Datetime: time.Now()}) + } + } + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for _, debt := range debts { + _, err := collection.InsertOne(ctx, debt) + if err != nil { + log.Fatal(err) + } + } +} From eab7fea353bbeeb3cb8eab2c64ff73bffb418d31 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 10:19:35 +0100 Subject: [PATCH 02/10] update 04.03.24 --- main.go | 337 +---------------------------------------------- router.go | 23 ++++ router/debt.go | 134 +++++++++++++++++++ router/person.go | 154 ++++++++++++++++++++++ util/util.go | 41 ++++++ 5 files changed, 355 insertions(+), 334 deletions(-) create mode 100644 router.go create mode 100644 router/debt.go create mode 100644 router/person.go diff --git a/main.go b/main.go index 28ea074..ba9feda 100644 --- a/main.go +++ b/main.go @@ -2,359 +2,28 @@ package main import ( "context" - "encoding/json" - "fmt" "gibb165lb2/util" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "log" "net/http" "time" - - "github.com/gorilla/mux" ) -var client *mongo.Client - -// func to insert 10 random persons with real names into the database and create 30 random debts for them - -func getDebtsForPerson(client *mongo.Client, personID string) ([]util.Debt, error) { - var results []util.Debt - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - // Umwandlung der personID von string in primitive.ObjectID - objID, err := primitive.ObjectIDFromHex(personID) - if err != nil { - return nil, err - } - - // Verbindung zur "debts" Sammlung - debtsCollection := client.Database("debtlist").Collection("debts") - - // Abfrage erstellen, die alle Schulden findet, deren fk_pid mit der personID übereinstimmt - filter := bson.M{"fk_pid": objID} - cursor, err := debtsCollection.Find(ctx, filter) - if err != nil { - return nil, err - } - defer cursor.Close(ctx) - - // Durchlaufen des Cursors und Hinzufügen der Ergebnisse zur results-Slice - for cursor.Next(ctx) { - var debt util.Debt - if err := cursor.Decode(&debt); err != nil { - return nil, err - } - results = append(results, debt) - } - - if err := cursor.Err(); err != nil { - return nil, err - } - - return results, nil -} - func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var err error - client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:root12345@localhost:27017")) + util.Client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:root12345@localhost:27017")) if err != nil { panic(err) } + //util.InsertRandomData(client) - // Router initialisieren - r := mux.NewRouter() - r.HandleFunc("/persons", createPerson).Methods("POST") - r.HandleFunc("/persons/{id}", getPerson).Methods("GET") - r.HandleFunc("/persons", getAllPersons).Methods("GET") - r.HandleFunc("/personsWithDebts", getPersonsWithDebts).Methods("GET") - r.HandleFunc("/persons/{id}", updatePerson).Methods("PUT") - r.HandleFunc("/persons/{id}", deletePerson).Methods("DELETE") - r.HandleFunc("/persons/{id}/debts", getDebts).Methods("GET") - r.HandleFunc("/persons/{id}/debts", createDebt).Methods("POST") - r.HandleFunc("/debts/{id}", deleteDebt).Methods("DELETE") - r.HandleFunc("/debts", getAllDebts).Methods("GET") - r.HandleFunc("/debts/{id}", getDebt).Methods("GET") - r.HandleFunc("/debts/{id}", updateDebt).Methods("PUT") + r := GetRouter() err = http.ListenAndServe(":3333", r) if err != nil { log.Fatal(err) } } - -func createPerson(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var person util.Person - json.NewDecoder(r.Body).Decode(&person) - collection := client.Database("debtlist").Collection("persons") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - result, err := collection.InsertOne(ctx, person) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - - } - json.NewEncoder(w).Encode(result) -} -func updatePerson(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var person util.Person - vars := mux.Vars(r) - personID := vars["id"] - person.ID, _ = primitive.ObjectIDFromHex(personID) - json.NewDecoder(r.Body).Decode(&person) - fmt.Println(person) - - collection := client.Database("debtlist").Collection("persons") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - filter := bson.M{"_id": person.ID} - update := bson.M{ - "$set": bson.M{ - "name": person.Name, - "age": person.Age, - "email": person.Email, - }, - } - result, err := collection.UpdateOne(ctx, filter, update) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - - } - json.NewEncoder(w).Encode(result) -} -func deletePerson(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - personID := vars["id"] - collection := client.Database("debtlist").Collection("persons") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - newPersonID, err := primitive.ObjectIDFromHex(personID) - filter := bson.M{"_id": newPersonID} - result, err := collection.DeleteOne(ctx, filter) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(result) -} -func getPerson(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - personID := vars["id"] - w.Header().Set("Content-Type", "application/json") - var person util.Person - collection := client.Database("debtlist").Collection("persons") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - pid, err := primitive.ObjectIDFromHex(personID) - filter := bson.M{"_id": pid} - err = collection.FindOne(ctx, filter).Decode(&person) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(person) -} -func getAllPersons(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var persons []util.Person - collection := client.Database("debtlist").Collection("persons") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - cursor, err := collection.Find(ctx, bson.M{}) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - defer cursor.Close(ctx) - for cursor.Next(ctx) { - var person util.Person - cursor.Decode(&person) - persons = append(persons, person) - } - if err := cursor.Err(); err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(persons) -} - -func getDebts(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - personID := vars["id"] - w.Header().Set("Content-Type", "application/json") - debts, err := getDebtsForPerson(client, personID) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(debts) -} - -func createDebt(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - w.Header().Set("Content-Type", "application/json") - var debt util.Debt - personID := vars["id"] - json.NewDecoder(r.Body).Decode(&debt) - debt.PersonID, _ = primitive.ObjectIDFromHex(personID) - collection := client.Database("debtlist").Collection("debts") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - result, err := collection.InsertOne(ctx, debt) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(result) -} - -func deleteDebt(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - w.Header().Set("Content-Type", "application/json") - var debt util.Debt - debtId := vars["id"] - json.NewDecoder(r.Body).Decode(&debt) - debt.ID, _ = primitive.ObjectIDFromHex(debtId) - collection := client.Database("debtlist").Collection("debts") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - filter := bson.M{"_id": debt.ID} - result, err := collection.DeleteOne(ctx, filter) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(result) -} - -func getAllDebts(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var debts []util.Debt - collection := client.Database("debtlist").Collection("debts") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - cursor, err := collection.Find(ctx, bson.M{}) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - defer cursor.Close(ctx) - for cursor.Next(ctx) { - var debt util.Debt - cursor.Decode(&debt) - debts = append(debts, debt) - } - if err := cursor.Err(); err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(debts) -} - -// eine route welche alle personen zurückgibt welche ein array aus debts haben. -func getPersonsWithDebts(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var personsWithDebts []util.PersonWithDebts - var persons []util.Person - collection := client.Database("debtlist").Collection("persons") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - cursor, err := collection.Find(ctx, bson.M{}) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - defer cursor.Close(ctx) - for cursor.Next(ctx) { - var person util.Person - cursor.Decode(&person) - persons = append(persons, person) - } - if err := cursor.Err(); err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - for _, person := range persons { - debts, err := getDebtsForPerson(client, person.ID.Hex()) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - personsWithDebts = append(personsWithDebts, util.PersonWithDebts{Person: person, Debts: debts}) - } - json.NewEncoder(w).Encode(personsWithDebts) -} - -// neue route welche eine einzelne debt zurückgibt -func getDebt(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - debtID := vars["id"] - w.Header().Set("Content-Type", "application/json") - var debt util.Debt - collection := client.Database("debtlist").Collection("debts") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - did, err := primitive.ObjectIDFromHex(debtID) - filter := bson.M{"_id": did} - err = collection.FindOne(ctx, filter).Decode(&debt) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(debt) -} - -// neue route welche eine einzelne debt aktualisiert -func updateDebt(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var debt util.Debt - vars := mux.Vars(r) - debtID := vars["id"] - debt.ID, _ = primitive.ObjectIDFromHex(debtID) - json.NewDecoder(r.Body).Decode(&debt) - collection := client.Database("debtlist").Collection("debts") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - filter := bson.M{"_id": debt.ID} - update := bson.M{ - "$set": bson.M{ - "fk_pid": debt.PersonID, - "amount": debt.Amount, - "description": debt.Description, - "datetime": debt.Datetime, - }, - } - result, err := collection.UpdateOne(ctx, filter, update) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"message": "` + err.Error() + `"}`)) - return - } - json.NewEncoder(w).Encode(result) -} diff --git a/router.go b/router.go new file mode 100644 index 0000000..8f11824 --- /dev/null +++ b/router.go @@ -0,0 +1,23 @@ +package main + +import ( + "gibb165lb2/router" + "github.com/gorilla/mux" +) + +func GetRouter() *mux.Router { + r := mux.NewRouter() + r.HandleFunc("/persons", router.CreatePerson).Methods("POST") + r.HandleFunc("/persons/{id}", router.GetPerson).Methods("GET") + r.HandleFunc("/persons", router.GetAllPersons).Methods("GET") + r.HandleFunc("/personsWithDebts", router.GetPersonsWithDebts).Methods("GET") + r.HandleFunc("/persons/{id}", router.UpdatePerson).Methods("PUT") + r.HandleFunc("/persons/{id}", router.DeletePerson).Methods("DELETE") + r.HandleFunc("/persons/{id}/debts", router.GetDebts).Methods("GET") + r.HandleFunc("/persons/{id}/debts", router.CreateDebt).Methods("POST") + r.HandleFunc("/debts/{id}", router.DeleteDebt).Methods("DELETE") + r.HandleFunc("/debts", router.GetAllDebts).Methods("GET") + r.HandleFunc("/debts/{id}", router.GetDebt).Methods("GET") + r.HandleFunc("/debts/{id}", router.UpdateDebt).Methods("PUT") + return r +} diff --git a/router/debt.go b/router/debt.go new file mode 100644 index 0000000..a01e991 --- /dev/null +++ b/router/debt.go @@ -0,0 +1,134 @@ +package router + +import ( + "context" + "encoding/json" + "gibb165lb2/util" + "github.com/gorilla/mux" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "net/http" + "time" +) + +func GetDebts(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + personID := vars["id"] + w.Header().Set("Content-Type", "application/json") + + debts, err := util.GetDebtsForPerson(util.Client, personID) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(debts) +} +func CreateDebt(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + personID := vars["id"] + json.NewDecoder(r.Body).Decode(&debt) + debt.PersonID, _ = primitive.ObjectIDFromHex(personID) + collection := util.Client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := collection.InsertOne(ctx, debt) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} +func DeleteDebt(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + debtId := vars["id"] + json.NewDecoder(r.Body).Decode(&debt) + debt.ID, _ = primitive.ObjectIDFromHex(debtId) + collection := util.Client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + filter := bson.M{"_id": debt.ID} + result, err := collection.DeleteOne(ctx, filter) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} +func GetAllDebts(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var debts []util.Debt + collection := util.Client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cursor, err := collection.Find(ctx, bson.M{}) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + defer cursor.Close(ctx) + for cursor.Next(ctx) { + var debt util.Debt + cursor.Decode(&debt) + debts = append(debts, debt) + } + if err := cursor.Err(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(debts) +} + +func GetDebt(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + debtID := vars["id"] + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + collection := util.Client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + did, err := primitive.ObjectIDFromHex(debtID) + filter := bson.M{"_id": did} + err = collection.FindOne(ctx, filter).Decode(&debt) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(debt) +} +func UpdateDebt(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var debt util.Debt + vars := mux.Vars(r) + debtID := vars["id"] + debt.ID, _ = primitive.ObjectIDFromHex(debtID) + json.NewDecoder(r.Body).Decode(&debt) + collection := util.Client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + filter := bson.M{"_id": debt.ID} + update := bson.M{ + "$set": bson.M{ + "fk_pid": debt.PersonID, + "amount": debt.Amount, + "description": debt.Description, + "datetime": debt.Datetime, + }, + } + result, err := collection.UpdateOne(ctx, filter, update) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} diff --git a/router/person.go b/router/person.go new file mode 100644 index 0000000..ee0c802 --- /dev/null +++ b/router/person.go @@ -0,0 +1,154 @@ +package router + +import ( + "context" + "encoding/json" + "fmt" + "gibb165lb2/util" + "github.com/gorilla/mux" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "net/http" + "time" +) + +func CreatePerson(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var person util.Person + json.NewDecoder(r.Body).Decode(&person) + collection := util.Client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := collection.InsertOne(ctx, person) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + + } + json.NewEncoder(w).Encode(result) +} +func UpdatePerson(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var person util.Person + vars := mux.Vars(r) + personID := vars["id"] + person.ID, _ = primitive.ObjectIDFromHex(personID) + json.NewDecoder(r.Body).Decode(&person) + fmt.Println(person) + + collection := util.Client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + filter := bson.M{"_id": person.ID} + update := bson.M{ + "$set": bson.M{ + "name": person.Name, + "age": person.Age, + "email": person.Email, + }, + } + result, err := collection.UpdateOne(ctx, filter, update) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + + } + json.NewEncoder(w).Encode(result) +} +func DeletePerson(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + vars := mux.Vars(r) + personID := vars["id"] + collection := util.Client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + newPersonID, err := primitive.ObjectIDFromHex(personID) + filter := bson.M{"_id": newPersonID} + result, err := collection.DeleteOne(ctx, filter) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(result) +} +func GetPerson(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + personID := vars["id"] + w.Header().Set("Content-Type", "application/json") + var person util.Person + collection := util.Client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + pid, err := primitive.ObjectIDFromHex(personID) + filter := bson.M{"_id": pid} + err = collection.FindOne(ctx, filter).Decode(&person) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(person) +} +func GetAllPersons(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var persons []util.Person + collection := util.Client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cursor, err := collection.Find(ctx, bson.M{}) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + defer cursor.Close(ctx) + for cursor.Next(ctx) { + var person util.Person + cursor.Decode(&person) + persons = append(persons, person) + } + if err := cursor.Err(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + json.NewEncoder(w).Encode(persons) +} +func GetPersonsWithDebts(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var personsWithDebts []util.PersonWithDebts + var persons []util.Person + collection := util.Client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cursor, err := collection.Find(ctx, bson.M{}) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + defer cursor.Close(ctx) + for cursor.Next(ctx) { + var person util.Person + cursor.Decode(&person) + persons = append(persons, person) + } + if err := cursor.Err(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + for _, person := range persons { + debts, err := util.GetDebtsForPerson(util.Client, person.ID.Hex()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"message": "` + err.Error() + `"}`)) + return + } + personsWithDebts = append(personsWithDebts, util.PersonWithDebts{Person: person, Debts: debts}) + } + json.NewEncoder(w).Encode(personsWithDebts) +} diff --git a/util/util.go b/util/util.go index 3e15609..35e46cc 100644 --- a/util/util.go +++ b/util/util.go @@ -2,12 +2,53 @@ package util import ( "context" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "log" "time" ) +var Client *mongo.Client + +func GetDebtsForPerson(client *mongo.Client, personID string) ([]Debt, error) { + var results []Debt + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Umwandlung der personID von string in primitive.ObjectID + objID, err := primitive.ObjectIDFromHex(personID) + if err != nil { + return nil, err + } + + // Verbindung zur "debts" Sammlung + debtsCollection := client.Database("debtlist").Collection("debts") + + // Abfrage erstellen, die alle Schulden findet, deren fk_pid mit der personID übereinstimmt + filter := bson.M{"fk_pid": objID} + cursor, err := debtsCollection.Find(ctx, filter) + if err != nil { + return nil, err + } + defer cursor.Close(ctx) + + // Durchlaufen des Cursors und Hinzufügen der Ergebnisse zur results-Slice + for cursor.Next(ctx) { + var debt Debt + if err := cursor.Decode(&debt); err != nil { + return nil, err + } + results = append(results, debt) + } + + if err := cursor.Err(); err != nil { + return nil, err + } + + return results, nil +} func InsertRandomData(client *mongo.Client) { persons := []string{"Max", "Moritz", "Hans", "Peter", "Paul", "Klaus", "Karl", "Kai", "Kurt", "Karl-Heinz"} debts := []Debt{} From 5b26df3e4c19a3fd5430e1ae4c8013ea684b0923 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 13:16:45 +0100 Subject: [PATCH 03/10] update 04.03.24 --- docker-compose.yaml | 14 +++++++++++--- src/Dockerfile | 9 +++++++++ go.mod => src/go.mod | 0 go.sum => src/go.sum | 0 main.go => src/main.go | 10 +++++++--- router.go => src/router.go | 2 ++ {router => src/router}/debt.go | 0 {router => src/router}/person.go | 0 {util => src/util}/structs.go | 0 {util => src/util}/util.go | 6 ++++++ 10 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 src/Dockerfile rename go.mod => src/go.mod (100%) rename go.sum => src/go.sum (100%) rename main.go => src/main.go (73%) rename router.go => src/router.go (93%) rename {router => src/router}/debt.go (100%) rename {router => src/router}/person.go (100%) rename {util => src/util}/structs.go (100%) rename {util => src/util}/util.go (94%) diff --git a/docker-compose.yaml b/docker-compose.yaml index 5af35ea..52fa689 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -2,11 +2,19 @@ version: "3.1" services: + backend: + build: ./src + restart: always + ports: + - "3333:3333" + environment: + - MONGO_URL=mongodb://root:root12345@mongo:27017/ + depends_on: + mongo: + condition: service_started mongo: image: mongo restart: always - ports: - - 27017:27017 environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: root12345 @@ -15,7 +23,7 @@ services: image: mongo-express restart: always ports: - - 8081:8081 + - "8081:8081" environment: ME_CONFIG_MONGODB_ADMINUSERNAME: root ME_CONFIG_MONGODB_ADMINPASSWORD: root12345 diff --git a/src/Dockerfile b/src/Dockerfile new file mode 100644 index 0000000..e0d5d25 --- /dev/null +++ b/src/Dockerfile @@ -0,0 +1,9 @@ +FROM golang:1.22 +LABEL authors="ZennDev1337" +WORKDIR /app +COPY go.mod go.sum ./ +RUN go mod download +COPY ./ ./ +RUN CGO_ENABLED=0 GOOS=linux go build -o /gibb165lb2 + +CMD ["/gibb165lb2"] \ No newline at end of file diff --git a/go.mod b/src/go.mod similarity index 100% rename from go.mod rename to src/go.mod diff --git a/go.sum b/src/go.sum similarity index 100% rename from go.sum rename to src/go.sum diff --git a/main.go b/src/main.go similarity index 73% rename from main.go rename to src/main.go index ba9feda..3004789 100644 --- a/main.go +++ b/src/main.go @@ -7,6 +7,7 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" "log" "net/http" + "os" "time" ) @@ -14,12 +15,15 @@ func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var err error - util.Client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:root12345@localhost:27017")) + var con_uri = os.Getenv("MONGO_URL") + if con_uri == "" { + con_uri = "mongodb://root:root12345@localhost:27017" + } + util.Client, err = mongo.Connect(ctx, options.Client().ApplyURI(con_uri)) if err != nil { panic(err) } - - //util.InsertRandomData(client) + defer util.Client.Disconnect(ctx) r := GetRouter() err = http.ListenAndServe(":3333", r) diff --git a/router.go b/src/router.go similarity index 93% rename from router.go rename to src/router.go index 8f11824..b91e96e 100644 --- a/router.go +++ b/src/router.go @@ -2,6 +2,7 @@ package main import ( "gibb165lb2/router" + "gibb165lb2/util" "github.com/gorilla/mux" ) @@ -19,5 +20,6 @@ func GetRouter() *mux.Router { r.HandleFunc("/debts", router.GetAllDebts).Methods("GET") r.HandleFunc("/debts/{id}", router.GetDebt).Methods("GET") r.HandleFunc("/debts/{id}", router.UpdateDebt).Methods("PUT") + r.HandleFunc("/init", util.Init).Methods("GET") return r } diff --git a/router/debt.go b/src/router/debt.go similarity index 100% rename from router/debt.go rename to src/router/debt.go diff --git a/router/person.go b/src/router/person.go similarity index 100% rename from router/person.go rename to src/router/person.go diff --git a/util/structs.go b/src/util/structs.go similarity index 100% rename from util/structs.go rename to src/util/structs.go diff --git a/util/util.go b/src/util/util.go similarity index 94% rename from util/util.go rename to src/util/util.go index 35e46cc..c7058e8 100644 --- a/util/util.go +++ b/src/util/util.go @@ -6,6 +6,7 @@ import ( "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "log" + "net/http" "time" ) @@ -75,3 +76,8 @@ func InsertRandomData(client *mongo.Client) { } } } + +func Init(w http.ResponseWriter, r *http.Request) { + InsertRandomData(Client) + w.Write([]byte("Init")) +} From 460c4cfbc5e560e185c02f7ba9547757ea082a1a Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 12:17:40 +0000 Subject: [PATCH 04/10] docker-compose.yaml aktualisiert --- docker-compose.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 52fa689..2b25c0d 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -8,7 +8,7 @@ services: ports: - "3333:3333" environment: - - MONGO_URL=mongodb://root:root12345@mongo:27017/ + - MONGO_URL: mongodb://root:root12345@mongo:27017/ depends_on: mongo: condition: service_started From 1e00f40d8d0597b2e7a052e9d58902fefbaa595f Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 13:19:22 +0100 Subject: [PATCH 05/10] update 04.03.24 --- docker-compose.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 2b25c0d..b649dbe 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,6 +1,4 @@ -# Use root/example as user/password credentials version: "3.1" - services: backend: build: ./src @@ -8,7 +6,7 @@ services: ports: - "3333:3333" environment: - - MONGO_URL: mongodb://root:root12345@mongo:27017/ + MONGO_URL: mongodb://root:root12345@mongo:27017/ depends_on: mongo: condition: service_started @@ -28,3 +26,4 @@ services: ME_CONFIG_MONGODB_ADMINUSERNAME: root ME_CONFIG_MONGODB_ADMINPASSWORD: root12345 ME_CONFIG_MONGODB_URL: mongodb://root:root12345@mongo:27017/ + \ No newline at end of file From e1591334847d58e65f18cff821afe948f6e64c16 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 14:11:56 +0100 Subject: [PATCH 06/10] update 04.03.24 --- docker-compose.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index b649dbe..c65ee1a 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -26,4 +26,3 @@ services: ME_CONFIG_MONGODB_ADMINUSERNAME: root ME_CONFIG_MONGODB_ADMINPASSWORD: root12345 ME_CONFIG_MONGODB_URL: mongodb://root:root12345@mongo:27017/ - \ No newline at end of file From e58ccfa22b8f675bb628f0147086556c3a5c98c2 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Mon, 4 Mar 2024 13:29:36 +0000 Subject: [PATCH 07/10] src/util/structs.go aktualisiert --- src/util/structs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/util/structs.go b/src/util/structs.go index 94ebfd0..94a9cad 100644 --- a/src/util/structs.go +++ b/src/util/structs.go @@ -16,7 +16,7 @@ type Debt struct { ID primitive.ObjectID `bson:"_id,omitempty"` PersonID primitive.ObjectID `bson:"fk_pid"` Amount int `bson:"amount"` - Description string `bson:"description,omitempty"` + Description string `bson:"description,omitempty" json:"description,omitempty"` Datetime time.Time `bson:"datetime"` } type PersonWithDebts struct { From 13344295907a13cdcb3e3fcdca33e859b2085812 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Tue, 5 Mar 2024 08:52:41 +0100 Subject: [PATCH 08/10] update 05.03.24 --- readme.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 readme.md diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..f0dc2a7 --- /dev/null +++ b/readme.md @@ -0,0 +1,32 @@ +# Gibb 165 LB 2 + +Ein Schulprojekt für NoSql-Databases + +## Voraussetzungen + +Stellen Sie sicher, dass die folgenden Tools auf Ihrem System installiert sind: + +- Docker +- Docker Compose + +## Installation + +1. Klone das Repository: + + ```bash + git clone https://repo.zenndev.xyz/Gibb-Projekte/modul-165-lb2 + ``` + +2. Wechsel in das Projektverzeichnis: + + ```bash + cd modul-165-lb2 + ``` + +3. Starte das Projekt mit Docker Compose: + + ```bash + docker-compose up -d + ``` + +4. Öffne deinen Webbrowser und gehe zu `http://localhost:3333`, um das Projekt zu sehen. From d7a1c59bec4f77495dff20f3005758abaa085667 Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Thu, 7 Mar 2024 09:54:09 +0100 Subject: [PATCH 09/10] update 07.03.24 --- .idea/.gitignore | 2 ++ readme.md | 2 ++ src/main.go | 3 ++- src/router.go | 1 + src/util/util.go | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 58 insertions(+), 1 deletion(-) diff --git a/.idea/.gitignore b/.idea/.gitignore index 13566b8..a9d7db9 100644 --- a/.idea/.gitignore +++ b/.idea/.gitignore @@ -6,3 +6,5 @@ # Datasource local storage ignored files /dataSources/ /dataSources.local.xml +# GitHub Copilot persisted chat sessions +/copilot/chatSessions diff --git a/readme.md b/readme.md index f0dc2a7..3008a7b 100644 --- a/readme.md +++ b/readme.md @@ -30,3 +30,5 @@ Stellen Sie sicher, dass die folgenden Tools auf Ihrem System installiert sind: ``` 4. Öffne deinen Webbrowser und gehe zu `http://localhost:3333`, um das Projekt zu sehen. + +# Todo diff --git a/src/main.go b/src/main.go index 3004789..4e4b05f 100644 --- a/src/main.go +++ b/src/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "gibb165lb2/util" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" @@ -25,7 +26,7 @@ func main() { } defer util.Client.Disconnect(ctx) r := GetRouter() - + fmt.Println("Server is running on port 3333") err = http.ListenAndServe(":3333", r) if err != nil { log.Fatal(err) diff --git a/src/router.go b/src/router.go index b91e96e..c2bd4d5 100644 --- a/src/router.go +++ b/src/router.go @@ -21,5 +21,6 @@ func GetRouter() *mux.Router { r.HandleFunc("/debts/{id}", router.GetDebt).Methods("GET") r.HandleFunc("/debts/{id}", router.UpdateDebt).Methods("PUT") r.HandleFunc("/init", util.Init).Methods("GET") + r.HandleFunc("/biginit", util.BigInit).Methods("GET") return r } diff --git a/src/util/util.go b/src/util/util.go index c7058e8..94c9da4 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -76,8 +76,59 @@ func InsertRandomData(client *mongo.Client) { } } } +func InsertRandomData2(client *mongo.Client) { + persons := []string{ + "John Smith", "Jane Doe", "Michael Johnson", "Emily Davis", "Christopher Wilson", + "Sarah Brown", "Matthew Anderson", "Jessica Miller", "William Taylor", "Olivia Garcia", + "David Martinez", "Ashley Jackson", "James White", "Emma Harris", "Daniel Thomas", + "Sophia Lee", "Joseph Moore", "Chloe Taylor", "Ryan Harris", "Mia Davis", + "Benjamin Clark", "Ava Williams", "Alexander Walker", "Grace Lewis", "Samuel Turner", + "Lily Martin", "Nicholas Harris", "Ella Thompson", "Tyler Baker", "Natalie Wright", + "Andrew Carter", "Aria Rodriguez", "Ethan Robinson", "Addison Turner", "Christopher Wright", + "Zoey Phillips", "Daniel Turner", "Victoria Brooks", "Nicholas Mitchell", "Scarlett Davis", + "Logan Wilson", "Penelope Anderson", "Caleb Baker", "Harper Martinez", "Dylan Turner", + "Layla Johnson", "Isaac Harris", "Stella Miller", "Nathan Jackson", "Sofia Clark", + "Brandon Walker", "Aurora Taylor", "Jackson Lewis", "Leah Anderson", "Owen Thompson", + "Maya Williams", "Caleb Lewis", "Addison Garcia", "Zachary Turner", "Brooklyn Wright", + "Christopher Davis", "Ellie Robinson", "Matthew Taylor", "Amelia Harris", "Gabriel Turner", + "Peyton Robinson", "Wyatt Anderson", "Zoe Martin", "Henry Harris", "Eva Phillips", + "Connor Wilson", "Scarlett Lee", "Dylan Baker", "Isabella Taylor", "Samuel Davis", + "Ava Turner", "Caleb Martinez", "Mia Walker", "Owen Lewis", "Abigail Johnson", + "Logan Clark", "Grace Harris", "Lucas Turner", "Madison Robinson", "Brayden Taylor", + "Lillian Anderson", "Jackson Martin", "Lily Harris", "Daniel Turner", "Riley Wright", + "Sebastian Turner", "Harper Davis", "Elijah Walker", "Addison Phillips", "Owen Harris", + "Chloe Robinson", "Ethan Anderson", "Zoe Taylor", "Gabriel Wilson", "Aurora Davis", + } + debts := []Debt{} + for i := 0; i < 100; i++ { + person := Person{Name: persons[i]} + collection := client.Database("debtlist").Collection("persons") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := collection.InsertOne(ctx, person) + if err != nil { + log.Fatal(err) + } + for j := 0; j < 6; j++ { + debts = append(debts, Debt{PersonID: result.InsertedID.(primitive.ObjectID), Amount: j * 100, Description: "Test", Datetime: time.Now()}) + } + } + collection := client.Database("debtlist").Collection("debts") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for _, debt := range debts { + _, err := collection.InsertOne(ctx, debt) + if err != nil { + log.Fatal(err) + } + } +} func Init(w http.ResponseWriter, r *http.Request) { InsertRandomData(Client) w.Write([]byte("Init")) } +func BigInit(w http.ResponseWriter, r *http.Request) { + InsertRandomData2(Client) + w.Write([]byte("Init")) +} From 6f61c68c9bb8a74785e1e3dbefc4bcbc35e66a1d Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Fri, 5 Apr 2024 13:23:48 +0200 Subject: [PATCH 10/10] first commit --- src/.idea/.gitignore | 8 ++ src/.idea/modules.xml | 8 ++ src/.idea/src.iml | 9 ++ src/.idea/vcs.xml | 6 ++ src/go.mod | 7 +- src/go.sum | 6 ++ src/main.go | 2 +- src/router.go | 39 ++++--- src/router/Laeden.go | 174 +++++++++++++++++++++++++++++++ src/router/Spiele.go | 236 ++++++++++++++++++++++++++++++++++++++++++ src/util/structs.go | 48 +++++++++ 11 files changed, 525 insertions(+), 18 deletions(-) create mode 100644 src/.idea/.gitignore create mode 100644 src/.idea/modules.xml create mode 100644 src/.idea/src.iml create mode 100644 src/.idea/vcs.xml create mode 100644 src/router/Laeden.go create mode 100644 src/router/Spiele.go diff --git a/src/.idea/.gitignore b/src/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/src/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/src/.idea/modules.xml b/src/.idea/modules.xml new file mode 100644 index 0000000..f669a0e --- /dev/null +++ b/src/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/src/.idea/src.iml b/src/.idea/src.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/src/.idea/src.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/.idea/vcs.xml b/src/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/src/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/go.mod b/src/go.mod index 22f5180..1321f98 100644 --- a/src/go.mod +++ b/src/go.mod @@ -2,16 +2,19 @@ module gibb165lb2 go 1.22 +require ( + github.com/gorilla/mux v1.8.1 + go.mongodb.org/mongo-driver v1.14.0 +) + require ( github.com/golang/snappy v0.0.1 // indirect - github.com/gorilla/mux v1.8.1 // indirect github.com/klauspost/compress v1.13.6 // indirect github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/scram v1.1.2 // indirect github.com/xdg-go/stringprep v1.0.4 // indirect github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect - go.mongodb.org/mongo-driver v1.14.0 // indirect golang.org/x/crypto v0.17.0 // indirect golang.org/x/sync v0.1.0 // indirect golang.org/x/text v0.14.0 // indirect diff --git a/src/go.sum b/src/go.sum index acc431a..6716fe6 100644 --- a/src/go.sum +++ b/src/go.sum @@ -1,5 +1,9 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= @@ -46,3 +50,5 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/src/main.go b/src/main.go index 4e4b05f..54c7380 100644 --- a/src/main.go +++ b/src/main.go @@ -26,7 +26,7 @@ func main() { } defer util.Client.Disconnect(ctx) r := GetRouter() - fmt.Println("Server is running on port 3333") + fmt.Println("Server is running on port 3000") err = http.ListenAndServe(":3333", r) if err != nil { log.Fatal(err) diff --git a/src/router.go b/src/router.go index c2bd4d5..a0ffc73 100644 --- a/src/router.go +++ b/src/router.go @@ -2,25 +2,34 @@ package main import ( "gibb165lb2/router" - "gibb165lb2/util" "github.com/gorilla/mux" ) func GetRouter() *mux.Router { r := mux.NewRouter() - r.HandleFunc("/persons", router.CreatePerson).Methods("POST") - r.HandleFunc("/persons/{id}", router.GetPerson).Methods("GET") - r.HandleFunc("/persons", router.GetAllPersons).Methods("GET") - r.HandleFunc("/personsWithDebts", router.GetPersonsWithDebts).Methods("GET") - r.HandleFunc("/persons/{id}", router.UpdatePerson).Methods("PUT") - r.HandleFunc("/persons/{id}", router.DeletePerson).Methods("DELETE") - r.HandleFunc("/persons/{id}/debts", router.GetDebts).Methods("GET") - r.HandleFunc("/persons/{id}/debts", router.CreateDebt).Methods("POST") - r.HandleFunc("/debts/{id}", router.DeleteDebt).Methods("DELETE") - r.HandleFunc("/debts", router.GetAllDebts).Methods("GET") - r.HandleFunc("/debts/{id}", router.GetDebt).Methods("GET") - r.HandleFunc("/debts/{id}", router.UpdateDebt).Methods("PUT") - r.HandleFunc("/init", util.Init).Methods("GET") - r.HandleFunc("/biginit", util.BigInit).Methods("GET") + r.HandleFunc("/spiele", router.GetSpiele).Methods("GET") + r.HandleFunc("/spiele", router.DeleteSpiel).Methods("DELETE") + r.HandleFunc("/laeden", router.GetLaeden).Methods("GET") + r.HandleFunc("/laeden", router.DeleteLaden).Methods("DELETE") + r.HandleFunc("/init", router.InitDatabase).Methods("GET") + r.HandleFunc("/spiele-mit-laeden", router.GetSpieleMitLaeden).Methods("GET") + r.HandleFunc("/spiele-mit-laeden", router.DeleteLadenFromSpiel).Methods("DELETE") + r.HandleFunc("/spiele-mit-laeden", router.AddNewLadenToSpiel).Methods("POST") + r.HandleFunc("/spiele", router.AddNewSpiel).Methods("POST") + r.HandleFunc("/laeden", router.AddNewLaden).Methods("POST") + //r.HandleFunc("/persons", router.CreatePerson).Methods("POST") + //r.HandleFunc("/persons/{id}", router.GetPerson).Methods("GET") + //r.HandleFunc("/persons", router.GetAllPersons).Methods("GET") + //r.HandleFunc("/personsWithDebts", router.GetPersonsWithDebts).Methods("GET") + //r.HandleFunc("/persons/{id}", router.UpdatePerson).Methods("PUT") + //r.HandleFunc("/persons/{id}", router.DeletePerson).Methods("DELETE") + //r.HandleFunc("/persons/{id}/debts", router.GetDebts).Methods("GET") + //r.HandleFunc("/persons/{id}/debts", router.CreateDebt).Methods("POST") + //r.HandleFunc("/debts/{id}", router.DeleteDebt).Methods("DELETE") + //r.HandleFunc("/debts", router.GetAllDebts).Methods("GET") + //r.HandleFunc("/debts/{id}", router.GetDebt).Methods("GET") + //r.HandleFunc("/debts/{id}", router.UpdateDebt).Methods("PUT") + //r.HandleFunc("/init", util.Init).Methods("GET") + //r.HandleFunc("/biginit", util.BigInit).Methods("GET") return r } diff --git a/src/router/Laeden.go b/src/router/Laeden.go new file mode 100644 index 0000000..410af97 --- /dev/null +++ b/src/router/Laeden.go @@ -0,0 +1,174 @@ +package router + +import ( + "context" + "encoding/json" + "gibb165lb2/util" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "math/rand" + "net/http" + "time" +) + +// curl -X GET localhost:3000/laeden +func GetLaeden(w http.ResponseWriter, r *http.Request) { + // MongoDB-Datenbank und -Sammlung auswählen + db := util.Client.Database("meineDatenbank") + laedenCollection := db.Collection("spielelaeden") + + // Läden aus der Datenbank abrufen + var laeden []util.Spieleladen + cursor, err := laedenCollection.Find(context.Background(), bson.M{}) + if err != nil { + log.Fatal(err) + } + defer cursor.Close(context.Background()) + for cursor.Next(context.Background()) { + var laden util.Spieleladen + if err := cursor.Decode(&laden); err != nil { + log.Fatal(err) + } + laeden = append(laeden, laden) + } + if err := cursor.Err(); err != nil { + log.Fatal(err) + } + + // Läden als JSON zurücksenden + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(laeden) +} + +// curl -X POST localhost:3000/initDatabase +func InitDatabase(w http.ResponseWriter, r *http.Request) { + // MongoDB-Datenbank und -Sammlungen auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + laedenCollection := db.Collection("spielelaeden") + + // Musterdaten für Läden und Spiele erstellen + laeden := []util.Spieleladen{ + {Name: "GameZone", Adresse: "123 Main Street", Telefonnummer: "555-1234"}, + {Name: "Gamer's Haven", Adresse: "456 Elm Street", Telefonnummer: "555-5678"}, + {Name: "TechZone", Adresse: "789 Oak Avenue", Telefonnummer: "555-9012"}, + {Name: "GameStop", Adresse: "321 Pine Road", Telefonnummer: "555-3456"}, + {Name: "Pixel Palace", Adresse: "555 Maple Lane", Telefonnummer: "555-7890"}, + } + + spiele := []util.Spiel{ + {Titel: "Red Dead Redemption 2", Erscheinungsdatum: time.Date(2018, 10, 26, 0, 0, 0, 0, time.UTC), Publisher: "Rockstar Games", Genre: "Action-Adventure", Plattform: "PlayStation 4", Bewertung: 10}, + {Titel: "The Legend of Zelda: Breath of the Wild", Erscheinungsdatum: time.Date(2017, 3, 3, 0, 0, 0, 0, time.UTC), Publisher: "Nintendo", Genre: "Action-Adventure", Plattform: "Nintendo Switch", Bewertung: 10}, + {Titel: "God of War", Erscheinungsdatum: time.Date(2018, 4, 20, 0, 0, 0, 0, time.UTC), Publisher: "Sony Interactive Entertainment", Genre: "Action-Adventure", Plattform: "PlayStation 4", Bewertung: 9}, + {Titel: "The Witcher 3: Wild Hunt", Erscheinungsdatum: time.Date(2015, 5, 19, 0, 0, 0, 0, time.UTC), Publisher: "CD Projekt", Genre: "Action-RPG", Plattform: "PlayStation 4", Bewertung: 9}, + } + + // Läden in die Datenbank einfügen + var laedenIDs []primitive.ObjectID + for _, l := range laeden { + result, err := laedenCollection.InsertOne(context.Background(), l) + if err != nil { + log.Fatal(err) + } + laedenIDs = append(laedenIDs, result.InsertedID.(primitive.ObjectID)) + } + + // Spiele in die Datenbank einfügen + var spieleWithLadenIDs []interface{} + for _, spiel := range spiele { + // Läden-IDs zum Spiel hinzufügen + ladenids := []primitive.ObjectID{} + randomIndex1 := rand.Intn(len(laedenIDs)) + ladenids = append(ladenids, laedenIDs[randomIndex1]) + var randomIndex2 int + for { + randomIndex2 = rand.Intn(len(laedenIDs)) + if randomIndex2 != randomIndex1 { + break + } + } + ladenids = append(ladenids, laedenIDs[randomIndex2]) + spiel.Laeden = ladenids + // Spiel in bson.M-Format konvertieren + spielBSON := bson.M{ + "Laeden": spiel.Laeden, + "Titel": spiel.Titel, + "Erscheinungsdatum": spiel.Erscheinungsdatum, + "Publisher": spiel.Publisher, + "Genre": spiel.Genre, + "Plattform": spiel.Plattform, + "Bewertung": spiel.Bewertung, + } + spieleWithLadenIDs = append(spieleWithLadenIDs, spielBSON) + } + _, err := spieleCollection.InsertMany(context.Background(), spieleWithLadenIDs) + if err != nil { + log.Fatal(err) + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusOK) + w.Write([]byte("Datenbank erfolgreich initialisiert")) +} + +// curl -X DELETE -d '{"laden_id": "YOUR_LADEN_ID"}' -H "Content-Type: application/json" localhost:3000/deleteLaden +func DeleteLaden(w http.ResponseWriter, r *http.Request) { + // Parse JSON body + var requestData struct { + LadenID string `json:"laden_id"` + } + err := json.NewDecoder(r.Body).Decode(&requestData) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Parse LadenID as ObjectID + ladenID, err := primitive.ObjectIDFromHex(requestData.LadenID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // MongoDB-Datenbank und -Sammlungen auswählen + db := util.Client.Database("meineDatenbank") + laedenCollection := db.Collection("spielelaeden") + + // Laden aus der Datenbank löschen + _, err = laedenCollection.DeleteOne(context.Background(), bson.M{"_id": ladenID}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusOK) + w.Write([]byte("Laden erfolgreich gelöscht")) +} + +// curl -X POST -d '{"name": "Neuer Laden", "adresse": "Neue Adresse", "telefonnummer": "123-456"}' -H "Content-Type: application/json" localhost:3000/addNewLaden +func AddNewLaden(w http.ResponseWriter, r *http.Request) { + // Parse JSON body + var newLaden util.Spieleladen + err := json.NewDecoder(r.Body).Decode(&newLaden) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // MongoDB-Datenbank und -Sammlung auswählen + db := util.Client.Database("meineDatenbank") + laedenCollection := db.Collection("spielelaeden") + + // Neuen Laden in die Datenbank einfügen + _, err = laedenCollection.InsertOne(context.Background(), newLaden) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusCreated) + w.Write([]byte("Neuer Laden erfolgreich erstellt")) +} diff --git a/src/router/Spiele.go b/src/router/Spiele.go new file mode 100644 index 0000000..5773b28 --- /dev/null +++ b/src/router/Spiele.go @@ -0,0 +1,236 @@ +package router + +import ( + "context" + "encoding/json" + "fmt" + "gibb165lb2/util" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "net/http" +) + +// curl -X GET localhost:3000/spiele +func GetSpiele(w http.ResponseWriter, r *http.Request) { + // MongoDB-Datenbank und -Sammlung auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + + // Spiele aus der Datenbank abrufen + var spiele []util.Spiel + cursor, err := spieleCollection.Find(context.Background(), bson.M{}) + if err != nil { + log.Fatal(err) + } + defer cursor.Close(context.Background()) + for cursor.Next(context.Background()) { + var spiel util.Spiel + if err := cursor.Decode(&spiel); err != nil { + log.Fatal(err) + } + spiele = append(spiele, spiel) + } + if err := cursor.Err(); err != nil { + log.Fatal(err) + } + + // Spiele als JSON zurücksenden + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(spiele) +} + +// curl -X DELETE -d '{"spiel_id": "YOUR_SPIEL_ID"}' -H "Content-Type: application/json" localhost:3000/deleteSpiel +func DeleteSpiel(w http.ResponseWriter, r *http.Request) { + // Parse JSON body + var requestData struct { + SpielID string `json:"spiel_id"` + } + err := json.NewDecoder(r.Body).Decode(&requestData) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Parse SpielID as ObjectID + spielID, err := primitive.ObjectIDFromHex(requestData.SpielID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // MongoDB-Datenbank und -Sammlungen auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + + // Spiel aus der Datenbank löschen + _, err = spieleCollection.DeleteOne(context.Background(), bson.M{"_id": spielID}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusOK) + w.Write([]byte("Spiel erfolgreich gelöscht")) +} + +// curl -X GET localhost:3000/spieleMitLaeden +func GetSpieleMitLaeden(w http.ResponseWriter, r *http.Request) { + // MongoDB-Datenbank und -Sammlungen auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + laedenCollection := db.Collection("spielelaeden") + + // Spiele aus der Datenbank abrufen + var spieleMitLaeden []util.SpieleMitLaden + cursor, err := spieleCollection.Find(context.Background(), bson.M{}) + if err != nil { + log.Fatal(err) + } + defer cursor.Close(context.Background()) + for cursor.Next(context.Background()) { + var spiel util.Spiel + if err := cursor.Decode(&spiel); err != nil { + log.Fatal(err) + } + spieleMitLaedenMut := spiel.ToSpieleMitLaden() + fmt.Printf("%+v\n", spieleMitLaedenMut) + // Lädeninformationen für jedes Spiel abrufen + for _, ladenID := range spiel.Laeden { + var laden util.Spieleladen + err := laedenCollection.FindOne(context.Background(), bson.M{"_id": ladenID}).Decode(&laden) + if err != nil { + log.Fatal(err) + } + spieleMitLaedenMut.Laeden = append(spieleMitLaedenMut.Laeden, laden) + } + spieleMitLaeden = append(spieleMitLaeden, spieleMitLaedenMut) + } + if err := cursor.Err(); err != nil { + log.Fatal(err) + } + + // Spiele mit Läden als JSON zurücksenden + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(spieleMitLaeden) +} + +// curl -X POST -d '{"titel": "Neues Spiel", "erscheinungsdatum": "2024-04-05T00:00:00Z", "publisher": "Neuer Publisher", "genre": "Neues Genre", "plattform": "Neue Plattform", "bewertung": 9}' -H "Content-Type: application/json" localhost:3000/addNewSpiel +func AddNewSpiel(w http.ResponseWriter, r *http.Request) { + // Parse JSON body + var newSpiel util.Spiel + err := json.NewDecoder(r.Body).Decode(&newSpiel) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // MongoDB-Datenbank und -Sammlung auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + + // Spiel in die Datenbank einfügen + _, err = spieleCollection.InsertOne(context.Background(), newSpiel) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusCreated) + w.Write([]byte("Neues Spiel erfolgreich hinzugefügt")) +} + +// curl -X POST -d '{"spiel_id": "YOUR_SPIEL_ID", "neuer_laden_id": "YOUR_NEUER_LADEN_ID"}' -H "Content-Type: application/json" localhost:3000/addNewLadenToSpiel +func AddNewLadenToSpiel(w http.ResponseWriter, r *http.Request) { + // Parse JSON body + var requestData struct { + SpielID string `json:"spiel_id"` + LadenID string `json:"neuer_laden_id"` + } + err := json.NewDecoder(r.Body).Decode(&requestData) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Parse SpielID as ObjectID + spielID, err := primitive.ObjectIDFromHex(requestData.SpielID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Parse NeuerLadenID as ObjectID + neuerLadenID, err := primitive.ObjectIDFromHex(requestData.LadenID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // MongoDB-Datenbank und -Sammlungen auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + + // Neuen Laden zur Spiel-Sammlung hinzufügen + _, err = spieleCollection.UpdateOne( + context.Background(), + bson.M{"_id": spielID}, + bson.M{"$push": bson.M{"Läden": neuerLadenID}}, + ) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusCreated) + w.Write([]byte("Neuer Laden erfolgreich zum Spiel hinzugefügt")) +} + +// curl -X DELETE -d '{"spiel_id": "YOUR_SPIEL_ID", "laden_id": "YOUR_LADEN_ID"}' -H "Content-Type: application/json" localhost:3000/deleteLadenFromSpiel +func DeleteLadenFromSpiel(w http.ResponseWriter, r *http.Request) { + // Parse JSON body + var requestData struct { + SpielID string `json:"spiel_id"` + LadenID string `json:"laden_id"` + } + err := json.NewDecoder(r.Body).Decode(&requestData) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Parse SpielID as ObjectID + spielID, err := primitive.ObjectIDFromHex(requestData.SpielID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Parse LadenID as ObjectID + ladenID, err := primitive.ObjectIDFromHex(requestData.LadenID) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + // MongoDB-Datenbank und -Sammlungen auswählen + db := util.Client.Database("meineDatenbank") + spieleCollection := db.Collection("spiele") + + // Laden aus der Spiel-Sammlung entfernen + _, err = spieleCollection.UpdateOne( + context.Background(), + bson.M{"_id": spielID}, + bson.M{"$pull": bson.M{"Läden": ladenID}}, + ) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Erfolgsmeldung senden + w.WriteHeader(http.StatusOK) + w.Write([]byte("Laden erfolgreich aus dem Spiel entfernt")) +} diff --git a/src/util/structs.go b/src/util/structs.go index 94a9cad..d63d56f 100644 --- a/src/util/structs.go +++ b/src/util/structs.go @@ -23,3 +23,51 @@ type PersonWithDebts struct { Person Person `json:"person"` Debts []Debt `json:"debts"` } + +// Spieleladen repräsentiert die Datenstruktur für die MongoDB-Sammlung "spielelaeden" +type Spieleladen struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"` + Name string `bson:"Name,omitempty" json:"Name,omitempty"` + Adresse string `bson:"Adresse,omitempty" json:"Adresse,omitempty"` + Telefonnummer string `bson:"Telefonnummer,omitempty" json:"Telefonnummer,omitempty"` +} + +// Spiel repräsentiert die Datenstruktur für die MongoDB-Sammlung "spiele" +type Spiel struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"` + Laeden []primitive.ObjectID `bson:"Laeden,omitempty" json:"Laeden,omitempty"` + Titel string `bson:"Titel,omitempty" json:"Titel,omitempty"` + Erscheinungsdatum time.Time `bson:"Erscheinungsdatum,omitempty" json:"Erscheinungsdatum,omitempty"` + Publisher string `bson:"Publisher,omitempty" json:"Publisher,omitempty"` + Genre string `bson:"Genre,omitempty" json:"Genre,omitempty"` + Plattform string `bson:"Plattform,omitempty" json:"Plattform,omitempty"` + Bewertung int `bson:"Bewertung,omitempty" json:"Bewertung,omitempty"` +} + +// SpieleMitLaden repräsentiert die Datenstruktur für die MongoDB-Sammlung "spiele" +type SpieleMitLaden struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"` + Laeden []Spieleladen `json:"Laeden,omitempty"` + LaedenId []primitive.ObjectID `bson:"Laeden,omitempty"` + Titel string `bson:"Titel,omitempty" json:"Titel,omitempty"` + Erscheinungsdatum time.Time `bson:"Erscheinungsdatum,omitempty" json:"Erscheinungsdatum,omitempty"` + Publisher string `bson:"Publisher,omitempty" json:"Publisher,omitempty"` + Genre string `bson:"Genre,omitempty" json:"Genre,omitempty"` + Plattform string `bson:"Plattform,omitempty" json:"Plattform,omitempty"` + Bewertung int `bson:"Bewertung,omitempty" json:"Bewertung,omitempty"` +} + +func (s Spiel) ToSpieleMitLaden() SpieleMitLaden { + spielmitladen := SpieleMitLaden{ + ID: s.ID, + Laeden: nil, + LaedenId: s.Laeden, + Titel: s.Titel, + Erscheinungsdatum: s.Erscheinungsdatum, + Publisher: s.Publisher, + Genre: s.Genre, + Plattform: s.Plattform, + Bewertung: s.Bewertung, + } + return spielmitladen +}