diff --git a/README.md b/README.md index bd2a79e..67852b1 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ To download and install this package run: *NOTE: if you need to grab as much info from a page as possible consider using [dyatlov/go-htmlinfo](https://github.com/dyatlov/go-htmlinfo)* +The package supports the whole set of OpenGraph properties from [The Open Graph protocol](https://ogp.me/). + ## Command line tool You can also use `opengraph` from CLI. @@ -20,17 +22,17 @@ Example usages: ```bash # download and parse html page -./opengraph https://www.youtube.com/watch?v=yhoI42bdwU4 +./opengraph https://www.youtube.com/watch\?v\=yhoI42bdwU4 ``` ```bash # parse piped html -curl https://www.youtube.com/watch?v=yhoI42bdwU4 | ./opengraph +curl https://www.youtube.com/watch\?v\=yhoI42bdwU4 | ./opengraph ``` ```bash # get video image -./opengraph https://www.youtube.com/watch?v=yhoI42bdwU4 | jq '.images[0].url' +./opengraph https://www.youtube.com/watch\?v\=yhoI42bdwU4 | jq '.images[0].url' ``` ## Package Methods diff --git a/cmd/opengraph/main.go b/cmd/opengraph/main.go index a5c2e3b..3c26214 100644 --- a/cmd/opengraph/main.go +++ b/cmd/opengraph/main.go @@ -16,43 +16,65 @@ package main import ( "bufio" "encoding/json" + "flag" "fmt" "io" "log" "net/http" + _url "net/url" "os" + "strings" "github.com/dyatlov/go-opengraph/opengraph" ) -func printHelp() { - fmt.Printf("Usage: %s \n", os.Args[0]) - os.Exit(0) -} +const appVersion = "1.0.1" func main() { + version := flag.Bool("v", false, "prints current opengraph version") + url := flag.String("url", "", "fetch url and extract OpenGraph info from there") + flag.Parse() + + if *version { + fmt.Println(appVersion) + return + } + + // allow url to be provided without flag too, by default + if *url == "" && flag.NArg() == 1 { + *url = flag.Arg(0) + } + + if *url != "" { + u, err := _url.ParseRequestURI(*url) + if err != nil { + log.Fatalf("Error parsing url: %s\n", err) + } else if !strings.HasPrefix(u.Scheme, "http") { + log.Fatal(u.Scheme) + log.Fatalf("URL should have http(s) protocol: %s\n", *url) + } + } + var reader io.Reader - if len(os.Args) == 2 { - url := os.Args[1] - resp, err := http.Get(url) + if *url != "" { + resp, err := http.Get(*url) if err != nil { - log.Fatalf("Error while fetching url %s: %s", url, err) + log.Fatalf("Error while fetching url %s: %s", *url, err) } reader = resp.Body defer resp.Body.Close() - } else if len(os.Args) == 1 { + } else { fi, _ := os.Stdin.Stat() if (fi.Mode() & os.ModeCharDevice) == 0 { // pipe reader = bufio.NewReader(os.Stdin) } else { - printHelp() + flag.Usage() + return } - } else { - printHelp() } og := opengraph.NewOpenGraph() diff --git a/cmd/opengraph/opengraph b/cmd/opengraph/opengraph index 08f0ea7..2ec020c 100755 Binary files a/cmd/opengraph/opengraph and b/cmd/opengraph/opengraph differ