xonecas.io
494
Ip

image-pal / files

image-pal / internal / routing.go

1.5 KB
1package imagePal
2
3import (
4	"io"
5	"net/http"
6	"strconv"
7
8	"github.com/gin-gonic/gin"
9)
10
11func GetImage(url string) (buffer []byte, contentType string, err error) {
12	imageRequest, err := http.Get(url)
13	if err != nil {
14		return nil, "", err
15	}
16	defer imageRequest.Body.Close()
17
18	buffer, err = io.ReadAll(imageRequest.Body)
19	if err != nil {
20		return nil, "", err
21	}
22
23	contentType = imageRequest.Header.Get("content-type")
24
25	return buffer, contentType, nil
26}
27
28type ResizeImageParams struct {
29	ImageUrl string `form:"image_url"`
30	Width    string `form:"width"`
31	Height   string `form:"height"`
32}
33
34func ResizeRoute(c *gin.Context) {
35	var params ResizeImageParams
36
37	if err := c.ShouldBind(&params); err != nil {
38		c.JSON(http.StatusBadRequest, gin.H{
39			"msg": err.Error(),
40		})
41		return
42	}
43
44	// TODO: Defaults for width and height
45	width, err := strconv.Atoi(params.Width)
46	if err != nil {
47		c.JSON(http.StatusInternalServerError, gin.H{
48			"msg": err.Error(),
49		})
50		return
51	}
52
53	height, err := strconv.Atoi(params.Height)
54	if err != nil {
55		c.JSON(http.StatusInternalServerError, gin.H{
56			"msg": err.Error(),
57		})
58		return
59	}
60
61	buffer, contentType, err := GetImage(params.ImageUrl)
62	if err != nil {
63		c.JSON(http.StatusInternalServerError, gin.H{
64			"msg": err.Error(),
65		})
66		return
67	}
68
69	resizedBuffer, err := Resize(
70		&buffer, width, height,
71	)
72	if err != nil {
73		c.JSON(http.StatusInternalServerError, gin.H{
74			"msg": err.Error(),
75		})
76		return
77	}
78
79	// TODO: Should we cache the result?
80	// err = bimg.Write(filename, resizedBuffer)
81
82	c.Data(http.StatusOK, contentType, resizedBuffer)
83}