Skip to content

Commit

Permalink
update: invalid url handling
Browse files Browse the repository at this point in the history
  • Loading branch information
abhijit-hota committed Apr 27, 2022
1 parent f1c72c0 commit 751325b
Showing 1 changed file with 24 additions and 14 deletions.
38 changes: 24 additions & 14 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package main

import (
"database/sql"
"errors"
"io"
"log"
"net/http"
"regexp"
"strings"
"time"

"github.com/atotto/clipboard"
Expand All @@ -14,38 +16,48 @@ import (
"golang.design/x/hotkey/mainthread"
)

func handleErr(err error) {
func handle(err error) {
if err != nil {
panic(err)
}
}

var db *sql.DB

func GetTitleFromURL(text string) (title string) {
res, err := http.Get(text)
handleErr(err)
func GetTitleFromURL(url string) (title string, err error) {
url = strings.TrimSpace(url)
if !(strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "https://")) {
url = "https://" + url
}
res, err := http.Get(url)
if err != nil {
return "", errors.New("Invalid URL.")
}

defer res.Body.Close()
resBytes, err := io.ReadAll(res.Body)
str := string(resBytes)
re := regexp.MustCompile("<title>(.+)</title>")

title = re.FindStringSubmatch(str)[1]
return
return title, nil
}

func SaveToDB(url string) {
GetTitleFromURL(url)
title := GetTitleFromURL(url)
title, err := GetTitleFromURL(url)

if err != nil {
log.Println(err)
return
}

stmt, err := db.Prepare("INSERT INTO LINKS (url, title, created, last_updated) VALUES (?, ?, ?, ?)")
handleErr(err)
handle(err)
defer stmt.Close()

now := time.Now().Unix()
_, err = stmt.Exec(url, title, now, now)
handleErr(err)
handle(err)

log.Println("Saved URL.")
}
Expand All @@ -54,7 +66,7 @@ func InitializeDB() {
var err error

db, err = sql.Open("sqlite3", "./links.db")
handleErr(err)
handle(err)

_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS links (
Expand All @@ -65,7 +77,7 @@ func InitializeDB() {
last_updated integer
)
`)
handleErr(err)
handle(err)
}

func ListenForHotKey() {
Expand All @@ -77,9 +89,7 @@ func ListenForHotKey() {

for range hk.Keydown() {
url, err := clipboard.ReadAll()
if err != nil {
panic(err)
}
handle(err)
SaveToDB(url)
}
}
Expand Down

0 comments on commit 751325b

Please sign in to comment.