Skip to content

Commit

Permalink
feat: accept additional query parameter in API endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
fedragon committed Jul 5, 2024
1 parent 64ea013 commit 63f02f9
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 16 deletions.
37 changes: 30 additions & 7 deletions api/bookmarks.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package api

import (
"fmt"
"log"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -32,14 +34,28 @@ func Handle(w http.ResponseWriter, r *http.Request) {
return
}

_, err := url.Parse(rawURL)
if err != nil {
tags := r.URL.Query()["tag"]

silent := strings.ToLower(r.URL.Query().Get("silent")) == "true"

fetchedAt := time.Now()
if rawEpoch := r.URL.Query().Get("epoch"); len(rawEpoch) > 0 {
epoch, err := strconv.Atoi(rawEpoch)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

if epoch > 0 {
fetchedAt = time.Unix(int64(epoch), 0)
}
}

if _, err := url.Parse(rawURL); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

tags := r.URL.Query()["tags"]

c := colly.NewCollector()
c.OnHTML("html", func(e *colly.HTMLElement) {
filename := time.Now().Format("20060102_150405")
Expand All @@ -57,20 +73,22 @@ func Handle(w http.ResponseWriter, r *http.Request) {
converter := md.NewConverter(e.Request.URL.Path, true, nil)
markdown, err := converter.ConvertBytes(body)
if err != nil {
log.Printf("failed to convert body to Markdown: %s\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

content := strings.Join(
[]string{
buildFrontmatter(e.Request.URL.String(), time.Now().Format(time.RFC3339), tags...),
buildFrontmatter(e.Request.URL.String(), fetchedAt.Format(time.RFC3339), tags...),
string(markdown),
},
"\n",
)

link, err := buildObsidianLink(vault, fmt.Sprintf("%s/%s", folder, filename), content)
link, err := buildObsidianLink(vault, fmt.Sprintf("%s/%s", folder, filename), content, silent)
if err != nil {
log.Printf("failed to build obsidian link: %s\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand All @@ -81,6 +99,7 @@ func Handle(w http.ResponseWriter, r *http.Request) {
})

if err := c.Visit(rawURL); err != nil {
log.Printf("failed to visit %s: %s\n", rawURL, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -112,7 +131,7 @@ func buildFrontmatter(url string, fetchedAt string, tags ...string) string {
)
}

func buildObsidianLink(vault string, path string, content string) (string, error) {
func buildObsidianLink(vault string, path string, content string, silent bool) (string, error) {
// mimic Javascript's encodeURIComponent, which is looser than Go's url.QueryEscape
encodeURIComponent := func(str string) string {
result := strings.Replace(str, "+", "%20", -1)
Expand All @@ -134,6 +153,10 @@ func buildObsidianLink(vault string, path string, content string) (string, error
values.Add("file", path)
values.Add("content", content)
values.Add("overwrite", "true")
if silent {
values.Add("silent", "true")
}

baseURL.RawQuery = encodeURIComponent(values.Encode())

return baseURL.String(), nil
Expand Down
2 changes: 1 addition & 1 deletion bookmarklet/src.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const tags = prompt("tags: ", "")
.split(",")
.map(tag => 'tags=' + encodeURIComponent(tag.trim()))
.map(tag => 'tag=' + encodeURIComponent(tag.trim()))
.join("&");

const addr = 'http://localhost:3333/api/bookmarks';
Expand Down
9 changes: 6 additions & 3 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,21 @@ import (
"github.com/kelseyhightower/envconfig"

"github.com/fedragon/bookmd/api"
"github.com/fedragon/bookmd/internal"
)

type Config struct {
HttpAddress string `envconfig:"BOOKMD_HTTP_ADDRESS" default:"0.0.0.0:3333"`
}

func main() {
config := internal.Config{}
config := Config{}
if err := envconfig.Process("", &config); err != nil {
log.Fatal(err)
}

router := chi.NewRouter()
router.Use(middleware.Logger)
router.Get("/bookmarks", api.Handle)
router.Get("/api/bookmarks", api.Handle)

server := &http.Server{Addr: config.HttpAddress, Handler: router}
serverCtx, serverStopCtx := context.WithCancel(context.Background())
Expand Down
5 changes: 0 additions & 5 deletions internal/config.go

This file was deleted.

0 comments on commit 63f02f9

Please sign in to comment.