update 04.03.24
This commit is contained in:
parent
eab7fea353
commit
5b26df3e4c
10 changed files with 35 additions and 6 deletions
9
src/Dockerfile
Normal file
9
src/Dockerfile
Normal file
|
@ -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"]
|
18
src/go.mod
Normal file
18
src/go.mod
Normal file
|
@ -0,0 +1,18 @@
|
|||
module gibb165lb2
|
||||
|
||||
go 1.22
|
||||
|
||||
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
|
||||
)
|
48
src/go.sum
Normal file
48
src/go.sum
Normal file
|
@ -0,0 +1,48 @@
|
|||
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
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=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
|
||||
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80=
|
||||
go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
|
||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
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=
|
33
src/main.go
Normal file
33
src/main.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gibb165lb2/util"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var err error
|
||||
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)
|
||||
}
|
||||
defer util.Client.Disconnect(ctx)
|
||||
r := GetRouter()
|
||||
|
||||
err = http.ListenAndServe(":3333", r)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
25
src/router.go
Normal file
25
src/router.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
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")
|
||||
return r
|
||||
}
|
134
src/router/debt.go
Normal file
134
src/router/debt.go
Normal file
|
@ -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)
|
||||
}
|
154
src/router/person.go
Normal file
154
src/router/person.go
Normal file
|
@ -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)
|
||||
}
|
25
src/util/structs.go
Normal file
25
src/util/structs.go
Normal file
|
@ -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"`
|
||||
}
|
83
src/util/util.go
Normal file
83
src/util/util.go
Normal file
|
@ -0,0 +1,83 @@
|
|||
package util
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"log"
|
||||
"net/http"
|
||||
"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{}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Init(w http.ResponseWriter, r *http.Request) {
|
||||
InsertRandomData(Client)
|
||||
w.Write([]byte("Init"))
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue