forked from harshmangalam/golang-react-image-upload-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (68 loc) · 2.39 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/google/uuid"
)
func main() {
// create new fiber instance and use across whole app
app := fiber.New()
// middleware to allow all clients to communicate using http and allow cors
app.Use(cors.New())
// serve images from images directory prefixed with /images
// i.e http://localhost:4000/images/someimage.webp
app.Static("/images", "./images")
// handle image uploading using post request
app.Post("/", handleFileupload)
// delete uploaded image by providing unique image name
app.Delete("/:imageName", handleDeleteImage)
// start dev server on port 4000
log.Fatal(app.Listen(":4000"))
}
func handleFileupload(c *fiber.Ctx) error {
// parse incomming image file
file, err := c.FormFile("image")
if err != nil {
log.Println("image upload error --> ", err)
return c.JSON(fiber.Map{"status": 500, "message": "Server error", "data": nil})
}
// generate new uuid for image name
uniqueId := uuid.New()
// remove "- from imageName"
filename := strings.Replace(uniqueId.String(), "-", "", -1)
// extract image extension from original file filename
fileExt := strings.Split(file.Filename, ".")[1]
// generate image from filename and extension
image := fmt.Sprintf("%s.%s", filename, fileExt)
// save image to ./images dir
err = c.SaveFile(file, fmt.Sprintf("./images/%s", image))
if err != nil {
log.Println("image save error --> ", err)
return c.JSON(fiber.Map{"status": 500, "message": "Server error", "data": nil})
}
// generate image url to serve to client using CDN
imageUrl := fmt.Sprintf("http://localhost:4000/images/%s", image)
// create meta data and send to client
data := map[string]interface{}{
"imageName": image,
"imageUrl": imageUrl,
"header": file.Header,
"size": file.Size,
}
return c.JSON(fiber.Map{"status": 201, "message": "Image uploaded successfully", "data": data})
}
func handleDeleteImage(c *fiber.Ctx) error {
// extract image name from params
imageName := c.Params("imageName")
// delete image from ./images
err := os.Remove(fmt.Sprintf("./images/%s", imageName))
if err != nil {
log.Println(err)
return c.JSON(fiber.Map{"status": 500, "message": "Server Error", "data": nil})
}
return c.JSON(fiber.Map{"status": 201, "message": "Image deleted successfully", "data": nil})
}