mirror of https://github.com/jlelse/GoBlog
Simplify shortpath code
This commit is contained in:
parent
fc31c6f088
commit
95233038f4
2
http.go
2
http.go
|
@ -226,7 +226,7 @@ func (a *goBlog) servePostsAliasesRedirects() http.HandlerFunc {
|
|||
select 'post', status, 200 from posts where path = @path
|
||||
union all
|
||||
-- short paths
|
||||
select 'alias', path, 301 from shortpath where printf('/s/`+"%"+`x', id) = @path
|
||||
select 'alias', path, 301 from shortpath where printf('/s/%x', id) = @path
|
||||
union all
|
||||
-- post aliases
|
||||
select 'alias', path, 302 from post_parameters where parameter = 'aliases' and value = @path
|
||||
|
|
57
shortPath.go
57
shortPath.go
|
@ -3,49 +3,38 @@ package main
|
|||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (db *database) shortenPath(p string) (string, error) {
|
||||
if p == "" {
|
||||
return "", errors.New("empty path")
|
||||
}
|
||||
idi, err, _ := db.sp.Do(p, func() (interface{}, error) {
|
||||
id := db.getShortPathID(p)
|
||||
if id == -1 {
|
||||
_, err := db.exec("insert or ignore into shortpath (path) values (@path)", sql.Named("path", p))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id = db.getShortPathID(p)
|
||||
spi, err, _ := db.sp.Do(p, func() (interface{}, error) {
|
||||
// Check if already cached
|
||||
if spi, ok := db.spc.Load(p); ok {
|
||||
return spi.(string), nil
|
||||
}
|
||||
return id, nil
|
||||
// Insert in case it isn't shortened yet
|
||||
_, err := db.exec("insert or ignore into shortpath (path) values (@path)", sql.Named("path", p))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Query short path
|
||||
row, err := db.queryRow("select printf('/s/%x', id) from shortpath where path = @path", sql.Named("path", p))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sp string
|
||||
err = row.Scan(&sp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Cache result
|
||||
db.spc.Store(p, sp)
|
||||
return sp, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id := idi.(int)
|
||||
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) {
|
||||
if p == "" {
|
||||
return -1
|
||||
}
|
||||
if idi, ok := db.spc.Load(p); ok {
|
||||
return idi.(int)
|
||||
}
|
||||
row, err := db.queryRow("select id from shortpath where path = @path", sql.Named("path", p))
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
err = row.Scan(&id)
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
db.spc.Store(p, id)
|
||||
return id
|
||||
return spi.(string), nil
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue