I have written a backend in Go for basic CRUD application. While working with Post function which can store images and other information in my DB the connection is getting terminated. This is what Thunderclient shows Connection was forcibly closed by a peer.
All other functions are working fine and the data is getting updated as per the requirement.
This is the helper function:
func Post(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "writer.FormDataContentType()")
w.Header().Set("Allow-Control-Allow-Methods", "POST")
err := r.ParseMultipartForm(32 << 20)
if err != nil {
panic(err)
}
params := mux.Vars(r)
category := r.FormValue("category")
description := r.FormValue("description")
file, _, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
fileBytes, err := io.ReadAll(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := models.Post{Image: fileBytes,
Category: category,
Description: description,
}
controllers.AddPost(params["id"], data)
json.NewEncoder(w).Encode(params["id"])
}
This is the controller:
func AddPost(user string, model models.Post) {
if Checkuserexists(user) {
id, err:= primitive.ObjectIDFromHex(user)
if err!=nil {
panic(err)
}
filter := bson.M{"_id":id}
update := bson.M{"$push":bson.M{"Posts":model}}
updated, err := Mongocollection.UpdateOne(context.Background(), filter, update)
if err!=nil {
panic(err)
}
println("updated", updated.ModifiedCount)
}
}
These are my models:
type Credentials struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Email string `json:"email" validate:"email, required" bson:"_email"`
Password string `json:"-"`
Posts []Post `json:"posts,omitempty" bson:"posts,omitempty"`
}
type Post struct {
ID primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
Image []byte `json:"image,omitempty" bson:"image"`
Category string `json:"category,omitempty" bson:"category"`
Description string `json:"description" bson:"description"`
}
I have all the dependencies installed. I tried changing the header but it didn't help. All other functions are working well.