This repository has been archived by the owner on Feb 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
120 lines (93 loc) · 2.03 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/weppos/publicsuffix-go/publicsuffix"
)
var (
// Version is replaced at compilation time
Version string
)
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
http.HandleFunc("/preview", PreviewServer)
http.ListenAndServe(":"+port, nil)
}
func PreviewServer(w http.ResponseWriter, r *http.Request) {
log.Printf("%v", r.URL)
w.Header().Set("X-Version", Version)
query := r.URL.Query()
var value string
pp := &PreviewParams{}
//if value = query.Get("r"); value == "" {
// fmt.Fprintf(w, "Parameter 'r' is missing")
// return
//}
//pp.setRules(value)
if value = query.Get("h"); value == "" {
fmt.Fprintf(w, "Parameter 'h' is missing")
return
}
pp.setHosts(value)
prs := preview(pp)
fmt.Fprintf(w, fmt.Sprintf("%v", prs))
}
type PreviewParams struct {
Rules []string
Hosts []string
}
func (p *PreviewParams) setRules(value string) error {
p.Rules = strings.Split(value, ",")
return nil
}
func (p *PreviewParams) setHosts(value string) error {
p.Hosts = strings.Split(value, ",")
return nil
}
type PreviewResults struct {
Results []PreviewResult
}
type PreviewResult struct {
Host string
Domain PreviewDomain
Error error
}
type PreviewDomain struct {
ETLD string
ETLDPlusOne string
Rule string
}
func newPreviewDomainFromPublicSuffix(d *publicsuffix.DomainName) *PreviewDomain {
if d == nil {
return nil
}
pd := &PreviewDomain{}
pd.ETLD = d.TLD
pd.ETLDPlusOne = d.SLD + "." + d.TLD
rule := d.Rule.Value
if d.Rule.Type == publicsuffix.WildcardType {
rule = "*." + rule
}
if d.Rule.Type == publicsuffix.ExceptionType {
rule = "!" + rule
}
pd.Rule = rule
return pd
}
func preview(pp *PreviewParams) *PreviewResults {
prs := &PreviewResults{}
for _, h := range pp.Hosts {
pr := PreviewResult{Host: h}
d, err := publicsuffix.Parse(pr.Host)
pr.Domain = *newPreviewDomainFromPublicSuffix(d)
pr.Error = err
prs.Results = append(prs.Results, pr)
}
return prs
}