/
pixel.go
62 lines (50 loc) · 1.51 KB
/
pixel.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
// Copyright 2024 E99p1ant. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package pixel
import (
"io"
"net/http"
"path"
"strconv"
"github.com/sirupsen/logrus"
"github.com/NekoWheel/NekoBox/internal/conf"
"github.com/NekoWheel/NekoBox/internal/context"
)
func Index(ctx context.Context) {
ctx.Success("pixel")
}
func Proxy(ctx context.Context) error {
uri := ctx.Param("**")
method := ctx.Request().Method
userID := strconv.Itoa(int(ctx.User.ID))
var body io.Reader
if method == http.MethodPost || method == http.MethodPut {
body = ctx.Request().Request.Body
}
req, err := http.NewRequest(method, "http://pixel/", body)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create request")
return ctx.ServerError()
}
req.URL.Host = conf.Pixel.Host
req.URL.Path = path.Join("/api/", uri)
req.Header.Set("neko-user-id", userID)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to send request")
return ctx.ServerError()
}
defer func() { _ = resp.Body.Close() }()
for k, v := range resp.Header {
ctx.ResponseWriter().Header()[k] = v
}
ctx.ResponseWriter().WriteHeader(resp.StatusCode)
_, err = io.Copy(ctx.ResponseWriter(), resp.Body)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to copy response")
return ctx.ServerError()
}
return nil
}