This repository has been archived by the owner on Oct 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (53 loc) · 1.64 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"strings"
"github.com/otiai10/opengraph"
)
type handler func(http.ResponseWriter, *http.Request) *serverError
type serverError struct {
code int
message string
}
func (f handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
http.Error(w, err.message, err.code)
}
}
func main() {
ua := flag.String("user-agent", "Ogjson/1.1", "Value of User-Agent")
flag.Parse()
http.Handle("/", handler(func(w http.ResponseWriter, r *http.Request) *serverError {
url := r.FormValue("url")
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return &serverError{http.StatusInternalServerError, err.Error()}
}
req.Header.Add("User-Agent", *ua)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return &serverError{http.StatusInternalServerError, err.Error()}
}
if resp.StatusCode >= http.StatusBadRequest {
return &serverError{resp.StatusCode, fmt.Sprintf("error response from %s: %s", url, resp.Status)}
}
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") {
return &serverError{http.StatusNotFound, `Content type of requested URL is not "text/html"`}
}
w.WriteHeader(resp.StatusCode)
og := opengraph.New(url)
if err = og.Parse(resp.Body); err != nil {
return &serverError{http.StatusInternalServerError, err.Error()}
}
w.Header().Set("Content-Type", "application/json")
if err = json.NewEncoder(w).Encode(og); err != nil {
return &serverError{http.StatusInternalServerError, err.Error()}
}
return nil
}))
log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}