aboutsummaryrefslogtreecommitdiff
path: root/src/server/handlers/image.go
blob: 99c9c181bea4e1eec4a8081cfda8f5be555ac5ac (plain)
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
package handlers

import (
	"net/http"
	"regexp"
	"server/database"
	"server/helper"
	"strconv"
)

func Image(writer http.ResponseWriter, request *http.Request) {
	if request.Method != "GET" {
		helper.WriteErrorJson("expected GET method", writer, http.StatusBadRequest)
		return
	}

	re := regexp.MustCompile(`^/image/([0-9]+).png$`)
	submatches := re.FindStringSubmatch(request.URL.Path)
	if len(submatches) != 2 {
		http.Error(writer, "invalid URL", http.StatusBadRequest)
		return
	}

	uid, err := strconv.Atoi(submatches[1])
	if err != nil {
		helper.WriteInternalError(err, writer)
		return
	}

	image_blob, err := database.GetImage(uid, request.URL.Query().Get("thumbnail") == "1")
	if err != nil {
		helper.WriteInternalError(err, writer)
		return
	}
	if image_blob == nil {
		http.Error(writer, "resource not found", http.StatusNotFound)
		return
	}

	writer.Write(image_blob)
}