From c185d463e685bd3f70e715a4ca34784c258e9ef6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20Hells=C3=A9n?= Date: Mon, 5 Feb 2024 02:35:46 +0100 Subject: [PATCH] Read HTML from a file instead of .tmpl --- .vscode/settings.json | 3 + go.mod | 2 + go.sum | 7 ++ html.go | 209 +++++++++++++++++++++++++++++++++++++++++ html_test.go | 50 ++++++++++ main.go | 31 ------ static/style.css | 57 ----------- templates/404.tmpl | 17 ---- templates/405.tmpl | 18 ---- templates/api.tmpl | 4 - templates/base.tmpl | 78 --------------- templates/donate.tmpl | 33 ------- templates/feeds.tmpl | 3 - templates/index.tmpl | 53 ----------- templates/privacy.tmpl | 50 ---------- templates/terms.tmpl | 34 ------- views.go | 161 ++++++++++++++++++------------- views_test.go | 152 +----------------------------- 18 files changed, 370 insertions(+), 592 deletions(-) create mode 100644 html.go create mode 100644 html_test.go delete mode 100644 static/style.css delete mode 100644 templates/404.tmpl delete mode 100644 templates/405.tmpl delete mode 100644 templates/api.tmpl delete mode 100644 templates/base.tmpl delete mode 100644 templates/donate.tmpl delete mode 100644 templates/feeds.tmpl delete mode 100644 templates/index.tmpl delete mode 100644 templates/privacy.tmpl delete mode 100644 templates/terms.tmpl diff --git a/.vscode/settings.json b/.vscode/settings.json index 875b190..8087d34 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,6 +12,7 @@ "bthub", "chartboost", "congstar", + "datetime", "easybox", "etxr", "feedburner", @@ -38,11 +39,13 @@ "PGPORT", "PGUSER", "regexes", + "Roboto", "routerlogin", "speedport", "steamloopback", "stretchr", "stylesheet", + "tdewolff", "tmpl", "tplinkap", "tplinkeap", diff --git a/go.mod b/go.mod index a309772..0ec92c5 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.21.6 require ( github.com/go-chi/chi/v5 v5.0.11 github.com/stretchr/testify v1.8.1 + github.com/tdewolff/minify/v2 v2.20.16 gorm.io/driver/sqlite v1.5.4 gorm.io/gorm v1.25.6 ) @@ -15,5 +16,6 @@ require ( github.com/jinzhu/now v1.1.5 // indirect github.com/mattn/go-sqlite3 v1.14.22 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/tdewolff/parse/v2 v2.7.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 4cd49f8..2924edb 100644 --- a/go.sum +++ b/go.sum @@ -18,6 +18,13 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/tdewolff/minify/v2 v2.20.16 h1:/C8dtRkxLTIyUlKlBz46gDiktCrE8a6+c1gTrnPFz+U= +github.com/tdewolff/minify/v2 v2.20.16/go.mod h1:/FvxV9KaTrFu35J9I2FhRvWSBxcHj8sDSdwBFh5voxM= +github.com/tdewolff/parse/v2 v2.7.11 h1:v+W45LnzmjndVlfqPCT5gGjAAZKd1GJGOPJveTIkBY8= +github.com/tdewolff/parse/v2 v2.7.11/go.mod h1:3FbJWZp3XT9OWVN3Hmfp0p/a08v4h8J9W1aghka0soA= +github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE= +github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739 h1:IkjBCtQOOjIn03u/dMQK9g+Iw9ewps4mCl1nB8Sscbo= +github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/html.go b/html.go new file mode 100644 index 0000000..0e141aa --- /dev/null +++ b/html.go @@ -0,0 +1,209 @@ +package main + +import ( + "fmt" + "strings" + + "github.com/tdewolff/minify/v2" + "github.com/tdewolff/minify/v2/css" + "github.com/tdewolff/minify/v2/html" +) + +type HTMLData struct { + Title string + Description string + Keywords string + Author string + CanonicalURL string + Content string +} + +func minifyHTML(h string) string { + m := minify.New() + m.AddFunc("text/html", html.Minify) + minified, err := m.String("text/html", h) + if err != nil { + return h + } + return minified +} + +func minifyCSS(h string) string { + m := minify.New() + m.AddFunc("text/css", css.Minify) + minified, err := m.String("text/css", h) + if err != nil { + return h + } + return minified +} + +var style = ` +html { + max-width: 70ch; + padding: calc(1vmin + 0.5rem); + margin-inline: auto; + font-size: clamp(1em, 0.909em + 0.45vmin, 1.25em); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + color-scheme: light dark; +} + +h1 { + font-size: 2.5rem; + font-weight: 600; + margin: 0; +} + +.title { + text-align: center; +} + +.search { + display: flex; + justify-content: center; + margin-top: 1rem; + margin-inline: auto; +} + +.leftright { + display: flex; + justify-content: center; +} + +.left { + margin-right: auto; +} + +.right { + margin-left: auto; +} + +textarea { + width: 100%; + height: 10rem; + resize: vertical; +} + +.messages { + list-style-type: none; +} + +.error { + color: red; +} + +.success { + color: green; +} +` + +func fullHTML(h HTMLData, ParseResult []ParseResult) string { + var sb strings.Builder + var errorBuilder strings.Builder + + FeedCount := 0 + DatabaseSize := GetDBSize() + + // This is the error message that will be displayed if there are any errors + if len(ParseResult) > 0 { + errorBuilder.WriteString("

Results

") + } + StatusMsg := errorBuilder.String() + + sb.WriteString(` + + + + + + + `) + + if h.Description != "" { + sb.WriteString(``) + } + + if h.Keywords != "" { + sb.WriteString(``) + } + + if h.Author != "" { + sb.WriteString(``) + } + + if h.CanonicalURL != "" { + sb.WriteString(``) + } + + sb.WriteString(` + ` + h.Title + ` + + + + ` + StatusMsg + ` +

FeedVault

+
+
+ Archive of web feeds. ` + fmt.Sprintf("%d", FeedCount) + ` feeds. ~` + DatabaseSize + `. +
+
+ +
+ + +
+
+
+ +
+
+ ` + h.Content + ` +
+
+ + + `) + + return minifyHTML(sb.String()) + +} diff --git a/html_test.go b/html_test.go new file mode 100644 index 0000000..78e5580 --- /dev/null +++ b/html_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "strings" + "testing" +) + +// returns a minified version of the input HTML string +func TestMinifyHTML(t *testing.T) { + input := "Test

Hello, World!

" + expected := "Test

Hello, World!

" + + result := minifyHTML(input) + + if result != expected { + t.Errorf("Expected minified HTML: %s, but got: %s", expected, result) + } +} + +func TestMinifyCSS(t *testing.T) { + cssString := ` + body { + background-color: red; + color: blue; + } + ` + expected := "body{background-color:red;color:blue}" + result := minifyCSS(cssString) + if result != expected { + t.Errorf("Expected minified CSS string to be %s, but got %s", expected, result) + } +} + +// Displays error messages if there are any parse errors +func TestErrorMessages(t *testing.T) { + // Initialize test data + h := HTMLData{} + parseResult := []ParseResult{ + {IsError: true, Msg: "Error 1"}, + {IsError: true, Msg: "Error 2"}, + } + + // Invoke function under test + result := fullHTML(h, parseResult) + + // Assert that the result contains the error messages + if !strings.Contains(result, "Error 1") || !strings.Contains(result, "Error 2") { + t.Errorf("Expected error messages, but got: %s", result) + } +} diff --git a/main.go b/main.go index 8e29185..fa265b7 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,6 @@ package main import ( - "fmt" - "html/template" "log" "net/http" @@ -53,38 +51,9 @@ func main() { // Routes r.Get("/", IndexHandler) r.Get("/api", ApiHandler) - r.Get("/donate", DonateHandler) r.Get("/feeds", FeedsHandler) - r.Get("/privacy", PrivacyHandler) - r.Get("/terms", TermsHandler) r.Post("/add", AddFeedHandler) - // Static files - r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) - - // 404 and 405 handlers - r.NotFound(NotFoundHandler) - r.MethodNotAllowed(MethodNotAllowedHandler) - log.Println("Listening on http://localhost:8000/ to stop") http.ListenAndServe("127.0.0.1:8000", r) } - -func renderPage(w http.ResponseWriter, title, description, keywords, author, url, templateName string) { - data := TemplateData{ - Title: title, - Description: description, - Keywords: keywords, - Author: author, - CanonicalURL: url, - FeedCount: 0, - } - data.GetDatabaseSizeAndFeedCount() - - t, err := template.ParseFiles("templates/base.tmpl", fmt.Sprintf("templates/%s.tmpl", templateName)) - if err != nil { - http.Error(w, fmt.Sprintf("Internal Server Error: %v", err), http.StatusInternalServerError) - return - } - t.ExecuteTemplate(w, "base", data) -} diff --git a/static/style.css b/static/style.css deleted file mode 100644 index f1b1a7d..0000000 --- a/static/style.css +++ /dev/null @@ -1,57 +0,0 @@ -html { - max-width: 70ch; - padding: calc(1vmin + 0.5rem); - margin-inline: auto; - font-size: clamp(1em, 0.909em + 0.45vmin, 1.25em); - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, - Arial, sans-serif; - color-scheme: light dark; -} - -h1 { - font-size: 2.5rem; - font-weight: 600; - margin: 0; -} - -.title { - text-align: center; -} - -.search { - display: flex; - justify-content: center; - margin-top: 1rem; - margin-inline: auto; -} - -.leftright { - display: flex; - justify-content: center; -} - -.left { - margin-right: auto; -} - -.right { - margin-left: auto; -} - -textarea { - width: 100%; - height: 10rem; - resize: vertical; -} - -.messages { - list-style-type: none; -} - -.error { - color: red; -} - -.success { - color: green; -} diff --git a/templates/404.tmpl b/templates/404.tmpl deleted file mode 100644 index 8e05203..0000000 --- a/templates/404.tmpl +++ /dev/null @@ -1,17 +0,0 @@ -{{ define "content" }} - -

404 - Page not found

-

Sorry, the page you are looking for does not exist.

-
-

-Extra information: -

-{{ end }} diff --git a/templates/405.tmpl b/templates/405.tmpl deleted file mode 100644 index 6482214..0000000 --- a/templates/405.tmpl +++ /dev/null @@ -1,18 +0,0 @@ -{{ define "content" }} - -

405 - Method Not Allowed

-

The method ({{ .Request.Method }}) is not allowed for the requested URL.

-
- -

-Extra information: -

-{{ end }} diff --git a/templates/api.tmpl b/templates/api.tmpl deleted file mode 100644 index f504e27..0000000 --- a/templates/api.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{{ define "content" }} -

API documentation

-

Here be dragons.

-{{ end }} diff --git a/templates/base.tmpl b/templates/base.tmpl deleted file mode 100644 index 2785657..0000000 --- a/templates/base.tmpl +++ /dev/null @@ -1,78 +0,0 @@ -{{ define "base" }} - - - - - - - {{ if .Description }}{{ end }} - {{ if .Keywords }}{{ end }} - {{ if .Author }}{{ end }} - {{ if .CanonicalURL }}{{ end }} - {{ .Title }} - - - - {{ if .ParseErrors }} -

Results

- - {{ end }} - - - -

- FeedVault -

-
-
-
- Archive of web feeds. {{ .FeedCount }} feeds. ~{{ .DatabaseSize }} -
-
- -
- - -
-
-
- -
- {{ block "content" . }}{{ end }} -
- - - -{{ end }} diff --git a/templates/donate.tmpl b/templates/donate.tmpl deleted file mode 100644 index 820d838..0000000 --- a/templates/donate.tmpl +++ /dev/null @@ -1,33 +0,0 @@ -{{ define "content" }} -

Donate

-

- tl;dr: GitHub Sponsors -

-

- FeedVault is a free service, and will always be free. However, if you wish to support the project, you can do so by donating to the developer. -

-

What will the money be used for?

-

- The money will be used to pay for the server costs, domain name, and other expenses related to running the service. -

-

How much does it cost to run FeedVault?

-

Domain name: 12 € / 13 $ / 10 £ per year

-

How can I donate?

-

- The preferred method of donating is through GitHub Sponsors due to no fees being taken. However, you can also donate through PayPal. -

-

Crypto

-

- You can also donate through cryptocurrency. The addresses are listed below. If you wish to donate through a cryptocurrency not listed below, please contact me. -

-

Bitcoin

-

- bc1qdgm09zzxllzh4m2edyyx7khwhw5mjrwe0d2dws -

-

Monero

-

- 83Hft9zJKPNgMrLAZQ7hhTBeJ6v9bJFJ7P7xfWLRDCiyg4QDwstnjc79Fdn5Y8uY5Hfddj52ok9JF8uisU9UXDJjT4Msevx -

-

Thank you!

-

Thank you for supporting FeedVault!

-{{ end }} diff --git a/templates/feeds.tmpl b/templates/feeds.tmpl deleted file mode 100644 index 5a4bd9d..0000000 --- a/templates/feeds.tmpl +++ /dev/null @@ -1,3 +0,0 @@ -{{ define "content" }} - Feeds -{{ end }} diff --git a/templates/index.tmpl b/templates/index.tmpl deleted file mode 100644 index cf83db6..0000000 --- a/templates/index.tmpl +++ /dev/null @@ -1,53 +0,0 @@ -{{ define "content" }} -

Feeds to archive

-

- Input the URLs of the feeds you wish to archive below. You can add as many as needed, and access them through the website or API. Alternatively, include links to .opml files, and the feeds within will be archived. -

-
- - -
-
-

You can also upload .opml files containing the feeds you wish to archive:

-
- - -
- -

FAQ

-
- What are web feeds? -

- Web feeds are a way to distribute content on the web. They allow users to access updates from websites without having to visit them directly. Feeds are typically used for news websites, blogs, and other sites that frequently update content. -
- You can read more about web feeds on Wikipedia. -

-
-
-
- What is FeedVault? -

- FeedVault is a service that archives web feeds. It allows users to access and search for historical content from various websites. The service is designed to preserve the history of the web and provide a reliable source for accessing content that may no longer be available on the original websites. -

-
-
-
- Why archive feeds? -

- Web feeds are a valuable source of information, and archiving them ensures that the content is preserved for future reference. By archiving feeds, we can ensure that historical content is available for research, analysis, and other purposes. Additionally, archiving feeds can help prevent the loss of valuable information due to website changes, outages, or other issues. -

-
-
-
- How does it work? -

- FeedVault is written in Go and uses the gofeed library to parse feeds. The service periodically checks for new content in the feeds and stores it in a database. Users can access the archived feeds through the website or API. -


-
-
- How can I access the archived feeds? -

- You can access the archived feeds through the website or API. The website provides a user interface for searching and browsing the feeds, while the API allows you to access the feeds programmatically. You can also download the feeds in various formats, such as JSON, XML, or RSS. -

-
-{{ end }} diff --git a/templates/privacy.tmpl b/templates/privacy.tmpl deleted file mode 100644 index d002c4a..0000000 --- a/templates/privacy.tmpl +++ /dev/null @@ -1,50 +0,0 @@ -{{ define "content" }} -
-
-

Privacy Policy

-
-

- Last Updated: - -

-
-

Information Collection

-

We gather the following data:

-
    -
  • Log Files: These files contain details about your IP address, browser, and operating system.
  • -
      -
    • This information is collected for debugging purposes and to enhance website performance.
    • -
    • Log files are automatically removed after a specific timeframe.
    • -
    • They are not linked to any personal information, shared with third parties, or used for marketing purposes.
    • -
    • Furthermore, log files are not utilized to track your activity on other websites.
    • -
    -
  • Cloudflare: We use Cloudflare to secure and optimize our website.
  • -
      -
    • Cloudflare may collect your IP address, cookies, and other data.
    • -
    • For more information, please review Cloudflare's privacy policy.
    • -
    -
-
-
-

User Rights

-

- You have the right to access, correct, or delete your information. Any privacy-related inquiries can be directed to us using the contact information provided at the end of this document. -

-
-
-

Changes to the Privacy Policy

-

- This privacy policy may be revised. You can review the revision history of this document on our GitHub repository here. -

-
-
-

Contact Information

-

- For privacy concerns or questions, you can reach us via email at hello@feedvault.se or by creating an issue on our GitHub repository. -

-

Cloudflare's contact information can be found here.

-
-
-{{ end }} diff --git a/templates/terms.tmpl b/templates/terms.tmpl deleted file mode 100644 index 5880947..0000000 --- a/templates/terms.tmpl +++ /dev/null @@ -1,34 +0,0 @@ -{{ define "content" }} -
-
-

Terms of Service

-
-

- Last Updated: - -

-
-

Content Policy

-

- Users are prohibited from uploading any content that is illegal under Swedish law. Any such content found on our platform will be removed. If this happens repeatedly, the user will be banned from using our platform. -
-
- You can report any content that you believe violates our content policy by sending an email to hello@feedvault.se. Please include the URL of the content in question and a brief description of why you believe it violates our content policy. -

-

Copyright Policy

-

- We will remove URLs that are used to share copyrightable information without the necessary permissions or licenses. -

-

Web Scraping

-

- Web scraping is permitted on our platform. We currently do not impose a rate limit on requests. -

-

API Usage

-

- Our API is free to use. We do not impose any rate limits on requests. -

-
-
-{{ end }} diff --git a/views.go b/views.go index 4653f1b..247a7d7 100644 --- a/views.go +++ b/views.go @@ -1,66 +1,106 @@ package main import ( - "fmt" - "html/template" "log" "net/http" "strings" ) -func NotFoundHandler(w http.ResponseWriter, r *http.Request) { - data := TemplateData{ - Request: r, - } - data.GetDatabaseSizeAndFeedCount() - t, err := template.ParseFiles("templates/base.tmpl", "templates/404.tmpl") - if err != nil { - http.Error(w, fmt.Sprintf("Internal Server Error: %v", err), http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusNotFound) - t.ExecuteTemplate(w, "base", data) -} - -func MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request) { - data := TemplateData{ - Request: r, - } - data.GetDatabaseSizeAndFeedCount() - t, err := template.ParseFiles("templates/base.tmpl", "templates/405.tmpl") - if err != nil { - http.Error(w, fmt.Sprintf("Internal Server Error: %v", err), http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusMethodNotAllowed) - t.ExecuteTemplate(w, "base", data) -} - func IndexHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "FeedVault", "FeedVault - A feed archive", "RSS, Atom, Feed, Archive", "TheLovinator", "http://localhost:8000/", "index") + + content := `

Feeds to archive

+

+ Input the URLs of the feeds you wish to archive below. You can add as many as needed, and access them through the website or API. Alternatively, include links to .opml files, and the feeds within will be archived. +

+
+ + +
+
+

You can also upload .opml files containing the feeds you wish to archive:

+
+ + +
+ ` + + FAQ := ` + +

FAQ

+
+ What are web feeds? +

+ Web feeds are a way to distribute content on the web. They allow users to access updates from websites without having to visit them directly. Feeds are typically used for news websites, blogs, and other sites that frequently update content. +
+ You can read more about web feeds on Wikipedia. +

+
+
+
+ What is FeedVault? +

+ FeedVault is a service that archives web feeds. It allows users to access and search for historical content from various websites. The service is designed to preserve the history of the web and provide a reliable source for accessing content that may no longer be available on the original websites. +

+
+
+
+ Why archive feeds? +

+ Web feeds are a valuable source of information, and archiving them ensures that the content is preserved for future reference. By archiving feeds, we can ensure that historical content is available for research, analysis, and other purposes. Additionally, archiving feeds can help prevent the loss of valuable information due to website changes, outages, or other issues. +

+
+
+
+ How does it work? +

+ FeedVault is written in Go and uses the gofeed library to parse feeds. The service periodically checks for new content in the feeds and stores it in a database. Users can access the archived feeds through the website or API. +


+
+
+ How can I access the archived feeds? +

+ You can access the archived feeds through the website or API. The website provides a user interface for searching and browsing the feeds, while the API allows you to access the feeds programmatically. You can also download the feeds in various formats, such as JSON, XML, or RSS. +

+
+ ` + + content += FAQ + + htmlData := HTMLData{ + Title: "FeedVault", + Description: "FeedVault - A feed archive", + Keywords: "RSS, Atom, Feed, Archive", + Author: "TheLovinator", + CanonicalURL: "http://localhost:8000/", + Content: content, + } + html := fullHTML(htmlData, nil) + w.Write([]byte(html)) } func ApiHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "API", "API Page", "api, page", "TheLovinator", "http://localhost:8000/api", "api") + htmlData := HTMLData{ + Title: "FeedVault API", + Description: "FeedVault API - A feed archive", + Keywords: "RSS, Atom, Feed, Archive, API", + Author: "TheLovinator", + CanonicalURL: "http://localhost:8000/api", + Content: "

Here be dragons.

", + } + html := fullHTML(htmlData, nil) + w.Write([]byte(html)) } -func AboutHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "About", "About Page", "about, page", "TheLovinator", "http://localhost:8000/about", "about") -} - -func DonateHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "Donate", "Donate Page", "donate, page", "TheLovinator", "http://localhost:8000/donate", "donate") -} - func FeedsHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "Feeds", "Feeds Page", "feeds, page", "TheLovinator", "http://localhost:8000/feeds", "feeds") -} - -func PrivacyHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "Privacy", "Privacy Page", "privacy, page", "TheLovinator", "http://localhost:8000/privacy", "privacy") -} - -func TermsHandler(w http.ResponseWriter, _ *http.Request) { - renderPage(w, "Terms", "Terms and Conditions Page", "terms, page", "TheLovinator", "http://localhost:8000/terms", "terms") + htmlData := HTMLData{ + Title: "FeedVault Feeds", + Description: "FeedVault Feeds - A feed archive", + Keywords: "RSS, Atom, Feed, Archive", + Author: "TheLovinator", + CanonicalURL: "http://localhost:8000/feeds", + Content: "

Here be feeds.

", + } + html := fullHTML(htmlData, nil) + w.Write([]byte(html)) } func AddFeedHandler(w http.ResponseWriter, r *http.Request) { @@ -88,20 +128,15 @@ func AddFeedHandler(w http.ResponseWriter, r *http.Request) { log.Println("Adding feed:", feed_url) } - // Render the index page with the parse errors - data := TemplateData{ - Title: "FeedVault", - Description: "FeedVault - A feed archive", - Keywords: "RSS, Atom, Feed, Archive", - ParseErrors: parseErrors, + htmlData := HTMLData{ + Title: "FeedVault - Add Feeds", + Description: "FeedVault - Add Feeds", + Keywords: "RSS, Atom, Feed, Archive", + Author: "TheLovinator", + CanonicalURL: "http://localhost:8000/add", + Content: "

Feeds added.

", } - data.GetDatabaseSizeAndFeedCount() - - t, err := template.ParseFiles("templates/base.tmpl", "templates/index.tmpl") - if err != nil { - http.Error(w, fmt.Sprintf("Internal Server Error: %v", err), http.StatusInternalServerError) - return - } - t.ExecuteTemplate(w, "base", data) + html := fullHTML(htmlData, parseErrors) + w.Write([]byte(html)) } diff --git a/views_test.go b/views_test.go index 18ff52f..f5b0e49 100644 --- a/views_test.go +++ b/views_test.go @@ -60,157 +60,7 @@ func TestApiHandler(t *testing.T) { } // Check the response contains the expected string. - shouldContain := "

Here be dragons.

" - body := rr.Body.String() - if !assert.Contains(t, body, shouldContain) { - t.Errorf("handler returned unexpected body: got %v want %v", - body, shouldContain) - } -} - -func TestTermsHandler(t *testing.T) { - // Create a request to pass to our handler. - req, err := http.NewRequest("GET", "/terms", nil) - if err != nil { - t.Fatal(err) - } - - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - rr := httptest.NewRecorder() - handler := http.HandlerFunc(TermsHandler) - - // Our handlers satisfy http.Handler, so we can call their ServeHTTP method - // directly and pass in our Request and ResponseRecorder. - handler.ServeHTTP(rr, req) - - // Check the status code is what we expect. - if status := rr.Code; status != http.StatusOK { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusOK) - } - - // Check the response contains the expected string. - shouldContain := "Terms of Service" - body := rr.Body.String() - if !assert.Contains(t, body, shouldContain) { - t.Errorf("handler returned unexpected body: got %v want %v", - body, shouldContain) - } -} - -func TestPrivacyHandler(t *testing.T) { - // Create a request to pass to our handler. - req, err := http.NewRequest("GET", "/privacy", nil) - if err != nil { - t.Fatal(err) - } - - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - rr := httptest.NewRecorder() - handler := http.HandlerFunc(PrivacyHandler) - - // Our handlers satisfy http.Handler, so we can call their ServeHTTP method - // directly and pass in our Request and ResponseRecorder. - handler.ServeHTTP(rr, req) - - // Check the status code is what we expect. - if status := rr.Code; status != http.StatusOK { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusOK) - } - - // Check the response contains the expected string. - shouldContain := "Privacy Policy" - body := rr.Body.String() - if !assert.Contains(t, body, shouldContain) { - t.Errorf("handler returned unexpected body: got %v want %v", - body, shouldContain) - } -} - -func TestNotFoundHandler(t *testing.T) { - // Create a request to pass to our handler. - req, err := http.NewRequest("GET", "/notfound", nil) - if err != nil { - t.Fatal(err) - } - - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - rr := httptest.NewRecorder() - handler := http.HandlerFunc(NotFoundHandler) - - // Our handlers satisfy http.Handler, so we can call their ServeHTTP method - // directly and pass in our Request and ResponseRecorder. - handler.ServeHTTP(rr, req) - - // Check the status code is what we expect. - if status := rr.Code; status != http.StatusNotFound { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusNotFound) - } - - // Check the response contains the expected string. - shouldContain := "

404 - Page not found

" - body := rr.Body.String() - if !assert.Contains(t, body, shouldContain) { - t.Errorf("handler returned unexpected body: got %v want %v", - body, shouldContain) - } -} - -func TestMethodNotAllowedHandler(t *testing.T) { - // Create a request to pass to our handler. - req, err := http.NewRequest("GET", "/api", nil) - if err != nil { - t.Fatal(err) - } - - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - rr := httptest.NewRecorder() - handler := http.HandlerFunc(MethodNotAllowedHandler) - - // Our handlers satisfy http.Handler, so we can call their ServeHTTP method - // directly and pass in our Request and ResponseRecorder. - handler.ServeHTTP(rr, req) - - // Check the status code is what we expect. - if status := rr.Code; status != http.StatusMethodNotAllowed { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusMethodNotAllowed) - } - - // Check the response contains the expected string. - shouldContain := "

405 - Method Not Allowed

" - body := rr.Body.String() - if !assert.Contains(t, body, shouldContain) { - t.Errorf("handler returned unexpected body: got %v want %v", - body, shouldContain) - } -} - -func TestDonateHandler(t *testing.T) { - // Create a request to pass to our handler. - req, err := http.NewRequest("GET", "/donate", nil) - if err != nil { - t.Fatal(err) - } - - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - rr := httptest.NewRecorder() - handler := http.HandlerFunc(DonateHandler) - - // Our handlers satisfy http.Handler, so we can call their ServeHTTP method - // directly and pass in our Request and ResponseRecorder. - handler.ServeHTTP(rr, req) - - // Check the status code is what we expect. - if status := rr.Code; status != http.StatusOK { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusOK) - } - - // Check the response contains the expected string. - shouldContain := "tl;dr: GitHub Sponsors" + shouldContain := "Here be dragons." body := rr.Body.String() if !assert.Contains(t, body, shouldContain) { t.Errorf("handler returned unexpected body: got %v want %v",