-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (74 loc) · 1.94 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
package main
import (
"context"
"log"
"net/http"
"strings"
"github.com/chromedp/chromedp"
)
func main() {
server := http.Server{Addr: ":9090"}
server.Handler = http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
sendJSON(w, 200, `{"status": "ok", "message": "Welcome to screenshot API"}`)
case "/api":
apiHandler(w, r)
default:
sendJSON(w, 404, `{"status": "error", "message": "Not found"}`)
}
},
)
log.Printf("[INFO] Listening on port 9090")
server.ListenAndServe()
}
func sendJSON(w http.ResponseWriter, status int, data string) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
w.Write([]byte(data))
}
var chromeOpts = []func(allocator *chromedp.ExecAllocator){
chromedp.ExecPath("/snap/bin/chromium"),
chromedp.Flag("disable-dev-shm-usage", true),
chromedp.Flag("disable-background-networking", true),
chromedp.WindowSize(1280, 720),
chromedp.DisableGPU,
chromedp.NoFirstRun,
chromedp.NoSandbox,
chromedp.Headless,
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
link := r.URL.Query().Get("url")
if link == "" {
sendJSON(w, 400, `{"status": "error", "message": "URL is required"}`)
return
}
if !strings.HasPrefix(link, "http") {
link = "http://" + link
}
log.Printf("[INFO] Link: %s", link)
allocatorCtx, allocatorCancel := chromedp.NewExecAllocator(
context.Background(),
chromeOpts...,
)
defer allocatorCancel()
ctx, cancel := chromedp.NewContext(allocatorCtx)
defer cancel()
var buf []byte
var title string
err := chromedp.Run(ctx, chromedp.Tasks{
chromedp.Navigate(link),
chromedp.Title(&title),
chromedp.FullScreenshot(&buf, 90),
})
if err != nil {
err_ := `{"status": "error", "message": "` + err.Error() + `"}`
sendJSON(w, 500, err_)
return
}
w.Header().Add("Content-Type", "image/jpeg")
w.Header().Add("Cache-Control", "no-cache")
w.Header().Add("X-Page-Title", title)
w.Write(buf)
}