-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (52 loc) · 1.12 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
package main
import (
"encoding/json"
"net/http"
"net/url"
"github.com/v-braun/hero-scrape"
"github.com/gorilla/mux"
"github.com/v-braun/hero-scrape-web/internal/logger"
)
func main() {
logger.On()
bndAddr := ":3001"
r := mux.NewRouter()
r.HandleFunc("/scrape", scrapeHandler).Methods("GET")
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./bin/")))
logger.Println("start webserver on addr %s", bndAddr)
err := http.ListenAndServe(bndAddr, r)
if err != nil {
panic(err)
}
}
func scrapeHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
u := query.Get("q")
if u == "" {
http.NotFound(w, r)
return
}
parsedURL, err := url.Parse(u)
if parsedURL == nil || err != nil {
http.NotFound(w, r)
return
}
res, err := http.Get(parsedURL.String())
if err != nil {
http.NotFound(w, r)
return
}
defer res.Body.Close()
result, _ := heroscrape.Scrape(parsedURL, res.Body)
if result == nil {
http.NotFound(w, r)
return
}
js, err := json.Marshal(result)
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}