/
main.go
165 lines (143 loc) · 3.93 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
nurl "net/url"
"os"
"strconv"
"strings"
readability "github.com/go-shiori/go-readability"
"github.com/spf13/cobra"
)
const index = `<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>go-readability</title>
</head>
<body>
<form action="/" style="width:80%">
<fieldset>
<legend>Get readability content</legend>
<p><label for="url">URL </label><input type="url" name="url" style="width:90%"></p>
<p><input type="checkbox" name="metadata" value="true">only get the page's metadata</p>
</fieldset>
<p><input type="submit"></p>
</form>
</body>
</html>`
func main() {
rootCmd := &cobra.Command{
Use: "go-readability [flags] [source]",
Run: rootCmdHandler,
Short: "go-readability is parser to fetch readable content of a web page",
Long: "go-readability is parser to fetch the readable content of a web page.\n" +
"The source can be an url or an existing file in your storage.",
}
rootCmd.Flags().StringP("http", "l", "", "start the http server at the specified address")
rootCmd.Flags().BoolP("metadata", "m", false, "only print the page's metadata")
err := rootCmd.Execute()
if err != nil {
log.Fatalln(err)
}
}
func rootCmdHandler(cmd *cobra.Command, args []string) {
// Start HTTP server
httpListen, _ := cmd.Flags().GetString("http")
if httpListen != "" {
http.HandleFunc("/", httpHandler)
log.Println("Starting HTTP server at", httpListen)
log.Fatal(http.ListenAndServe(httpListen, nil))
}
// Get cmd parameter
metadataOnly, _ := cmd.Flags().GetBool("metadata")
if len(args) > 0 {
content, err := getContent(args[0], metadataOnly)
if err != nil {
log.Fatalln(err)
}
fmt.Println(content)
} else {
cmd.Help()
}
}
func httpHandler(w http.ResponseWriter, r *http.Request) {
metadata := r.URL.Query().Get("metadata")
metadataOnly, _ := strconv.ParseBool(metadata)
url := r.URL.Query().Get("url")
if url == "" {
w.Write([]byte(index))
} else {
log.Println("process URL", url)
content, err := getContent(url, metadataOnly)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if metadataOnly {
w.Header().Set("Content-Type", "application/json")
}
w.Write([]byte(content))
}
}
func getContent(srcPath string, metadataOnly bool) (string, error) {
// Open or fetch web page that will be parsed
var (
pageURL *nurl.URL
srcReader io.Reader
)
if url, isURL := validateURL(srcPath); isURL {
resp, err := http.Get(srcPath)
if err != nil {
return "", fmt.Errorf("failed to fetch web page: %v", err)
}
defer resp.Body.Close()
pageURL = url
srcReader = resp.Body
} else {
srcFile, err := os.Open(srcPath)
if err != nil {
return "", fmt.Errorf("failed to open source file: %v", err)
}
defer srcFile.Close()
pageURL, _ = nurl.ParseRequestURI("http://fakehost.com")
srcReader = srcFile
}
// Use tee so the reader can be used twice
buf := bytes.NewBuffer(nil)
tee := io.TeeReader(srcReader, buf)
// Make sure the page is readable
if !readability.Check(tee) {
return "", fmt.Errorf("failed to parse page: the page is not readable")
}
// Get readable content from the reader
article, err := readability.FromReader(buf, pageURL)
if err != nil {
return "", fmt.Errorf("failed to parse page: %v", err)
}
// Return the article (or its metadata)
if metadataOnly {
metadata := map[string]interface{}{
"title": article.Title,
"byline": article.Byline,
"excerpt": article.Excerpt,
"image": article.Image,
"favicon": article.Favicon,
}
prettyJSON, err := json.MarshalIndent(&metadata, "", " ")
if err != nil {
return "", fmt.Errorf("failed to write metadata file: %v", err)
}
return string(prettyJSON), nil
}
return article.Content, nil
}
func validateURL(path string) (*nurl.URL, bool) {
url, err := nurl.ParseRequestURI(path)
return url, err == nil && strings.HasPrefix(url.Scheme, "http")
}