From e0f74c5a30506ac39fc8f71ceb784de929df6f34 Mon Sep 17 00:00:00 2001 From: Nebojsa Ilic Date: Sun, 6 Aug 2023 11:35:57 +0200 Subject: [PATCH] add base URL to output (#3) * add from url link * fix method name * add base url to list output --- cmd/hntop/output.go | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/cmd/hntop/output.go b/cmd/hntop/output.go index 5d466ea..41f37db 100644 --- a/cmd/hntop/output.go +++ b/cmd/hntop/output.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" ht "html/template" + "net/url" tt "text/template" "time" @@ -13,6 +14,7 @@ import ( ) const ( + fromBaseURL = "https://news.ycombinator.com/from?site=" itemBaseURL = "https://news.ycombinator.com/item?id=" userBaseURL = "https://news.ycombinator.com/user?id=" mailSubject = "[hntop] Top HN posts" @@ -20,7 +22,7 @@ const ( listTemplate = `{{if .FrontPage}}Displaying HN posts currently on the front page{{else}}Displaying top {{.ResultCount}} HN posts from {{.StartTime}} to {{.EndTime}}{{end -}} {{if .Hits}} {{range $i, $e := .Hits}} -{{increment $i}}. {{.Title}} +{{increment $i}}. {{.Title}}{{if ne .GetBaseExternalURL ""}} ({{.GetBaseExternalURL}}){{end}} {{.GetExternalURL}} {{- if ne .GetItemURL .GetExternalURL}} {{.GetItemURL}} @@ -33,7 +35,7 @@ const ( {{else}}Top {{.ResultCount}} HN posts from {{.StartTime}} to {{.EndTime}}{{end}}

{{if .Hits}} {{range $i, $e := .Hits}} - {{increment $i}}. {{.Title}}
+ {{increment $i}}. {{.Title}}{{if ne .GetBaseExternalURL ""}} ({{.GetBaseExternalURL}}){{end}}
{{.Points}} points by {{.Author}} {{timeAgo .CreatedAt}} | {{.NumComments}} comments

{{end}} {{end}}` @@ -146,6 +148,29 @@ func (h Hit) GetUserURL() string { return userBaseURL + h.Author } +func (h Hit) GetBaseExternalURL() string { + if h.URL == "" { + return "" + } + + u, err := url.Parse(h.URL) + if err != nil { + return "" + } + + return u.Hostname() +} + +func (h Hit) GetFromURL() string { + b := h.GetBaseExternalURL() + + if b == "" { + return "" + } + + return fromBaseURL + b +} + func increment(i int) int { return i + 1 }