aboutsummaryrefslogtreecommitdiff
path: root/route/routes/api.go
blob: 70607e98b0836bb9eca87cd0bc8757b5aec73b1c (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package routes

import (
	"io/ioutil"
	"net/http"
	"time"

	"github.com/FChannel0/FChannel-Server/config"
	"github.com/FChannel0/FChannel-Server/util"
	"github.com/gofiber/fiber/v2"
)

func Media(ctx *fiber.Ctx) error {
	if ctx.Query("hash") != "" {
		return RouteImages(ctx, ctx.Query("hash"))
	}

	return ctx.SendStatus(404)
}

func RouteImages(ctx *fiber.Ctx, media string) error {
	req, err := http.NewRequest("GET", config.MediaHashs[media], nil)
	if err != nil {
		return util.MakeError(err, "RouteImages")
	}

	client := http.Client{
		Timeout: 5 * time.Second,
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		fileBytes, err := ioutil.ReadFile("./static/notfound.png")
		if err != nil {
			return util.MakeError(err, "RouteImages")
		}

		_, err = ctx.Write(fileBytes)
		return util.MakeError(err, "RouteImages")
	}

	body, _ := ioutil.ReadAll(resp.Body)
	for name, values := range resp.Header {
		for _, value := range values {
			ctx.Append(name, value)
		}
	}

	return ctx.Send(body)
}