2020-12-22 22:15:29 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
|
2021-03-03 18:19:55 +01:00
|
|
|
"github.com/go-chi/chi/v5"
|
2020-12-22 22:15:29 +01:00
|
|
|
)
|
|
|
|
|
2021-06-06 14:39:42 +02:00
|
|
|
func (db *database) shortenPath(p string) (string, error) {
|
2020-12-22 22:15:29 +01:00
|
|
|
if p == "" {
|
|
|
|
return "", errors.New("empty path")
|
|
|
|
}
|
2021-06-06 14:39:42 +02:00
|
|
|
id := db.getShortPathID(p)
|
2020-12-22 22:15:29 +01:00
|
|
|
if id == -1 {
|
2021-06-06 14:39:42 +02:00
|
|
|
_, err := db.exec("insert or ignore into shortpath (path) values (@path)", sql.Named("path", p))
|
2020-12-22 22:15:29 +01:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2021-06-06 14:39:42 +02:00
|
|
|
id = db.getShortPathID(p)
|
2020-12-22 22:15:29 +01:00
|
|
|
}
|
|
|
|
if id == -1 {
|
|
|
|
return "", errors.New("failed to retrieve short path for " + p)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("/s/%x", id), nil
|
|
|
|
}
|
|
|
|
|
2021-06-06 14:39:42 +02:00
|
|
|
func (db *database) getShortPathID(p string) (id int) {
|
2020-12-22 22:15:29 +01:00
|
|
|
if p == "" {
|
|
|
|
return -1
|
|
|
|
}
|
2021-06-06 14:39:42 +02:00
|
|
|
row, err := db.queryRow("select id from shortpath where path = @path", sql.Named("path", p))
|
2020-12-22 22:15:29 +01:00
|
|
|
if err != nil {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
err = row.Scan(&id)
|
|
|
|
if err != nil {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return id
|
|
|
|
}
|
|
|
|
|
2021-06-06 14:39:42 +02:00
|
|
|
func (a *goBlog) redirectToLongPath(rw http.ResponseWriter, r *http.Request) {
|
2020-12-22 22:15:29 +01:00
|
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 16, 64)
|
|
|
|
if err != nil {
|
2021-06-06 14:39:42 +02:00
|
|
|
a.serve404(rw, r)
|
2020-12-22 22:15:29 +01:00
|
|
|
return
|
|
|
|
}
|
2021-06-06 14:39:42 +02:00
|
|
|
row, err := a.db.queryRow("select path from shortpath where id = @id", sql.Named("id", id))
|
2020-12-22 22:15:29 +01:00
|
|
|
if err != nil {
|
2021-06-06 14:39:42 +02:00
|
|
|
a.serve404(rw, r)
|
2020-12-22 22:15:29 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
var path string
|
|
|
|
err = row.Scan(&path)
|
|
|
|
if err != nil {
|
2021-06-06 14:39:42 +02:00
|
|
|
a.serve404(rw, r)
|
2020-12-22 22:15:29 +01:00
|
|
|
return
|
|
|
|
}
|
2020-12-22 23:26:23 +01:00
|
|
|
http.Redirect(rw, r, path, http.StatusMovedPermanently)
|
2020-12-22 22:15:29 +01:00
|
|
|
}
|