blogs and event api : Get and Post methods

This commit is contained in:
gom-by
2025-01-16 14:45:18 +01:00
parent 9a6e4a7565
commit 0c5a411ed1
5 changed files with 174 additions and 91 deletions

View File

@@ -3,50 +3,49 @@ package api
import (
"context"
"encoding/json"
"fmt"
"log"
"io"
"net/http"
"time"
core "fr.latosa-escrima/api/core"
"github.com/uptrace/bun"
)
func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
emptyObject := make(map[string]interface{})
emptyJSON, json_err := json.Marshal(emptyObject)
if json_err != nil {
fmt.Println("Couldn't create the json object")
w.Write(emptyJSON)
}
if r.Method != http.MethodPost {
core.JSONError{
Status: core.Error,
Message: "Method is not allowed",
}.Respond(w, http.StatusMethodNotAllowed)
return
}
err := r.ParseForm()
body, err := io.ReadAll(r.Body)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
var blog core.Blog
if err = json.Unmarshal(body, &blog); err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
_, err = core.DB.NewInsert().Model(blog).Exec(context.Background())
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNotAcceptable)
}
user := &core.Blog{
BaseModel: bun.BaseModel{},
BlogID: [16]byte{},
Slug: "",
Content: "",
Label: "",
AuthorID: [16]byte{},
Published: time.Time{},
Summary: "",
Image: "",
Href: "",
Author: &core.User{},
}
_, err_db := core.DB.NewInsert().Model(user).Exec(context.Background())
if err_db != nil {
log.Fatal(err)
}
fmt.Println("User inserted successfully")
core.JSONSuccess{
Status: core.Success,
Message: "Blog inserted",
Data: blog,
}.Respond(w, http.StatusCreated)
}