~handlerug/handlebot

ref: e2138e35984f582b50a481b58c332afae2841b1f handlebot/urlpreview/urlpreview.go -rw-r--r-- 833 bytes
e2138e35Umar Getagazov urlpreview: Parse Content-Disposition 5 months ago
                                                                                
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
package urlpreview

import (
	"context"
	"net"
	"net/http"
	"net/url"

	"git.sr.ht/~adnano/go-gemini"
)

type Previewer struct {
	HttpClient   http.Client
	GeminiClient gemini.Client
}

func (p *Previewer) Preview(ctx context.Context, u *url.URL) (string, error) {
	hostname := u.Hostname()
	if hostname == "localhost" {
		return "", nil
	}
	if ip := net.ParseIP(hostname); ip != nil && ip.IsLoopback() {
		return "", nil
	}

	var (
		res      string
		err      error
		handlers []func(context.Context, *url.URL) (string, error)
	)

	switch u.Scheme {
	case "http", "https":
		handlers = append(handlers, p.youtube, p.wolframalpha, p.jisho,
			p.generic)
	case "gemini":
		handlers = append(handlers, p.gemini)
	}
	for _, h := range handlers {
		res, err = h(ctx, u)
		if res != "" || err != nil {
			break
		}
	}
	return res, err
}