Compare commits

..

2 Commits

Author SHA1 Message Date
554719f566 refactor: return redirect instead of json
All checks were successful
/ build-and-push-image (push) Successful in 1m19s
2024-08-05 12:16:55 +03:00
eeca427725 refactor: move handlers to seperate file 2024-08-05 10:18:15 +03:00
2 changed files with 136 additions and 105 deletions

119
handlers/handlers.go Normal file
View File

@ -0,0 +1,119 @@
package handlers
import (
"fmt"
"io"
"os"
"strings"
DB "log101/konulu-konum-backend/db"
"log101/konulu-konum-backend/models"
"github.com/dchest/uniuri"
"github.com/gofiber/fiber/v2"
"github.com/h2non/bimg"
"gorm.io/gorm"
)
func KonuluKonumCreate(c *fiber.Ctx) error {
clientURL := os.Getenv("CLIENT_URL")
if form, err := c.MultipartForm(); err == nil {
// Get form values
author := form.Value["author"][0]
description := form.Value["description"][0]
// Geolocation is stored as JSON array string
geolocation := fmt.Sprintf("[%s]", form.Value["geolocation"][0])
file := form.File["selected-photo"][0]
newFile, err := file.Open()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
defer newFile.Close()
// Read image file
data, err := io.ReadAll(newFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Compress image file and convert to webp
newImage, err := bimg.NewImage(data).Convert(bimg.WEBP)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Save image file in public folder
imageName := strings.Split(file.Filename, ".")[0]
imagePath := fmt.Sprintf("./public/%s.webp", imageName)
imageURL := fmt.Sprintf("%s.webp", imageName)
err = bimg.Write(imagePath, newImage)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Generate public uri for the image this will be the
// id for the konulu konum
chars := uniuri.StdChars[26:52]
randomUri := uniuri.NewLenChars(10, chars)
imageUri := fmt.Sprintf("%s-%s-%s", randomUri[0:3], randomUri[3:7], randomUri[7:])
// Write to DB
db := DB.GetDB()
db.Create(&models.KonuluKonum{URI: imageUri, ImageURL: imageURL, Coordinates: geolocation, AuthorName: author, Description: description, UnlockedCounter: 0})
// Return URL
redirectURL := fmt.Sprintf("%s/x?id=%s", clientURL, imageUri)
return c.Redirect(redirectURL)
}
redirectUrl := fmt.Sprintf("%s?error=%s", clientURL, "true")
return c.Redirect(redirectUrl)
}
func KonuluKonumGet(c *fiber.Ctx) error {
uri := c.Params("locationUri")
if len(uri) == 0 {
return c.SendStatus(fiber.StatusBadRequest)
}
var konuluKonum models.KonuluKonum
db := DB.GetDB()
rows := db.Where("URI = ?", uri).First(&konuluKonum)
if rows.Error != nil {
return c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON(fiber.Map{
"url": konuluKonum.URI,
"blob_url": konuluKonum.ImageURL,
"loc": konuluKonum.Coordinates,
"author": konuluKonum.AuthorName,
"description": konuluKonum.Description,
"unlocked_counter": konuluKonum.UnlockedCounter,
})
}
func KonuluKonumCounterUpdate(c *fiber.Ctx) error {
uri := c.Params("locationUri")
if len(uri) == 0 {
return c.SendStatus(fiber.StatusBadRequest)
}
var konuluKonum models.KonuluKonum
db := DB.GetDB()
rows := db.Where("URI = ?", uri).First(&konuluKonum)
if rows.Error != nil {
return c.SendStatus(fiber.StatusNotFound)
}
rows = db.Model(&konuluKonum).Where("uri = ?", uri).UpdateColumn("unlocked_counter", gorm.Expr("unlocked_counter + 1"))
if rows.Error != nil {
c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON(fiber.Map{
"counter": konuluKonum.ID,
})
}

122
server.go
View File

@ -1,22 +1,15 @@
package main package main
import ( import (
"fmt"
"io"
"log" "log"
DB "log101/konulu-konum-backend/db" DB "log101/konulu-konum-backend/db"
"log101/konulu-konum-backend/models" "log101/konulu-konum-backend/handlers"
"strings"
"os" "os"
"github.com/dchest/uniuri"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/logger"
"github.com/h2non/bimg"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"gorm.io/gorm"
) )
func main() { func main() {
@ -26,114 +19,33 @@ func main() {
log.Println("Error loading .env file") log.Println("Error loading .env file")
} }
// initialize db // Create public folder for images
err = os.Mkdir("public", 0750)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
// Initialize db
DB.InitDB() DB.InitDB()
db := DB.GetDB()
app := fiber.New() app := fiber.New()
app.Use(logger.New()) app.Use(logger.New())
app.Use(cors.New(cors.Config{ app.Use(cors.New(cors.Config{
AllowOrigins: "http://localhost:4321", AllowOrigins: "http://localhost:4321",
})) }))
// Serve static images
app.Static("/images", "./public") app.Static("/images", "./public")
app.Get("/", func(c *fiber.Ctx) error { // Create konulu konum
return c.SendString("Sample") app.Post("/api/location", handlers.KonuluKonumCreate)
})
app.Post("/api/location", func(c *fiber.Ctx) error { // Get konulu konum
if form, err := c.MultipartForm(); err == nil { app.Get("/api/location/:locationUri", handlers.KonuluKonumGet)
// Get form values
author := form.Value["author"][0]
description := form.Value["description"][0]
geolocation := fmt.Sprintf("[%s]", form.Value["geolocation"][0])
file := form.File["selected-photo"][0] // Update 'seen' counter of konulu konum
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0]) // This is shown at the bottom of the web page
app.Patch("/api/location/increment/:locationUri", handlers.KonuluKonumCounterUpdate)
newFile, err := file.Open()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
defer newFile.Close()
data, err := io.ReadAll(newFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Compress image
newImage, err := bimg.NewImage(data).Convert(bimg.WEBP)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
imageName := strings.Split(file.Filename, ".")[0]
imagePath := fmt.Sprintf("./public/%s.webp", imageName)
imageURL := fmt.Sprintf("%s.webp", imageName)
err = bimg.Write(imagePath, newImage)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Generate public uri for the image
chars := uniuri.StdChars[26:52]
randomUri := uniuri.NewLenChars(10, chars)
imageUri := fmt.Sprintf("%s-%s-%s", randomUri[0:3], randomUri[3:7], randomUri[7:])
db.Create(&models.KonuluKonum{URI: imageUri, ImageURL: imageURL, Coordinates: geolocation, AuthorName: author, Description: description, UnlockedCounter: 0})
return c.JSON(fiber.Map{
"url": imageUri,
})
}
return c.SendStatus(fiber.StatusBadRequest)
})
app.Get("/api/location/:locationUri", func(c *fiber.Ctx) error {
uri := c.Params("locationUri")
if len(uri) == 0 {
return c.SendStatus(fiber.StatusBadRequest)
}
var konuluKonum models.KonuluKonum
rows := db.Where("URI = ?", uri).First(&konuluKonum)
if rows.Error != nil {
return c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON(fiber.Map{
"url": konuluKonum.URI,
"blob_url": konuluKonum.ImageURL,
"loc": konuluKonum.Coordinates,
"author": konuluKonum.AuthorName,
"description": konuluKonum.Description,
"unlocked_counter": konuluKonum.UnlockedCounter,
})
})
app.Patch("/api/location/increment/:locationUri", func(c *fiber.Ctx) error {
uri := c.Params("locationUri")
if len(uri) == 0 {
return c.SendStatus(fiber.StatusBadRequest)
}
var konuluKonum models.KonuluKonum
rows := db.Where("URI = ?", uri).First(&konuluKonum)
if rows.Error != nil {
return c.SendStatus(fiber.StatusNotFound)
}
rows = db.Model(&konuluKonum).Where("uri = ?", uri).UpdateColumn("unlocked_counter", gorm.Expr("unlocked_counter + 1"))
if rows.Error != nil {
c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON(fiber.Map{
"counter": konuluKonum.ID,
})
})
app.Listen(":3456") app.Listen(":3456")
} }