This repository has been archived by the owner on Jan 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (70 loc) · 2 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
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func main() {
apiKey := os.Getenv("SERVER_API_KEY")
iframelyKey := os.Getenv("IFRAMELY_API_KEY")
if apiKey == "" || iframelyKey == "" {
fmt.Println("Environment variables SERVER_API_KEY and IFRAMELY_API_KEY must be set")
return
}
app := fiber.New()
app.Use(cors.New())
app.Get("/info", func(c *fiber.Ctx) error {
target := c.Query("url")
key := c.Query("api_key")
if subtle.ConstantTimeCompare([]byte(key), []byte(apiKey)) == 0 {
return fiber.NewError(fiber.StatusBadRequest, "Invalid API key")
}
u, err := url.Parse("https://iframe.ly/api/oembed")
query := u.Query()
query.Add("api_key", iframelyKey)
query.Add("iframe", "0")
query.Add("url", target)
u.RawQuery = query.Encode()
ctx, cancel := context.WithTimeout(c.Context(), time.Duration(time.Second))
defer cancel()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
req = req.WithContext(ctx)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("failed to fetch data: %s", resp.Status))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
var iframelyResp IframelyResponse
err = json.Unmarshal(body, &iframelyResp)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(Response{
Provider: strings.ToLower(iframelyResp.ProviderName),
URL: iframelyResp.URL,
HTML: iframelyResp.HTML,
Image: iframelyResp.ThumbnailURL,
Error: iframelyResp.Error,
})
})
err := app.Listen(":3000")
log.Fatal(err)
}