GoBlog/shortPath.go

41 lines
886 B
Go
Raw Normal View History

2020-12-22 21:15:29 +00:00
package main
import (
"database/sql"
"errors"
)
func (db *database) shortenPath(p string) (string, error) {
2020-12-22 21:15:29 +00:00
if p == "" {
return "", errors.New("empty path")
}
2021-11-09 09:50:03 +00:00
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
2020-12-22 21:15:29 +00:00
}
2021-11-09 09:50:03 +00:00
// 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
2021-07-03 10:11:57 +00:00
})
if err != nil {
return "", err
2020-12-22 21:15:29 +00:00
}
2021-11-09 09:50:03 +00:00
return spi.(string), nil
2020-12-22 21:15:29 +00:00
}