Simple blogging system written in Go https://goblog.app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
GoBlog/shortPath.go

65 lines
1.3 KiB

2 years ago
package main
import (
"database/sql"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
2 years ago
)
func (db *database) shortenPath(p string) (string, error) {
2 years ago
if p == "" {
return "", errors.New("empty path")
}
id := db.getShortPathID(p)
2 years ago
if id == -1 {
_, err := db.exec("insert or ignore into shortpath (path) values (@path)", sql.Named("path", p))
2 years ago
if err != nil {
return "", err
}
id = db.getShortPathID(p)
2 years ago
}
if id == -1 {
return "", errors.New("failed to retrieve short path for " + p)
}
return fmt.Sprintf("/s/%x", id), nil
}
func (db *database) getShortPathID(p string) (id int) {
2 years ago
if p == "" {
return -1
}
row, err := db.queryRow("select id from shortpath where path = @path", sql.Named("path", p))
2 years ago
if err != nil {
return -1
}
err = row.Scan(&id)
if err != nil {
return -1
}
return id
}
func (a *goBlog) redirectToLongPath(rw http.ResponseWriter, r *http.Request) {
2 years ago
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 16, 64)
if err != nil {
a.serve404(rw, r)
2 years ago
return
}
row, err := a.db.queryRow("select path from shortpath where id = @id", sql.Named("id", id))
2 years ago
if err != nil {
a.serve404(rw, r)
2 years ago
return
}
var path string
err = row.Scan(&path)
if err != nil {
a.serve404(rw, r)
2 years ago
return
}
http.Redirect(rw, r, path, http.StatusMovedPermanently)
2 years ago
}