Added proper redirection, improved loading error display

This commit is contained in:
Christopher Ramey 2018-11-24 04:07:39 +00:00 committed by cdramey
parent 7ebbfc8da9
commit b3ee5c5e1b
4 changed files with 47 additions and 2 deletions

View File

@ -61,7 +61,7 @@ func loadjson(stor storage.Storage, filename string) error {
err := q.CheckValid()
if err != nil {
fmt.Printf("\nValidation failure: %s\n", err.Error())
fmt.Printf("\n%s\nValidation failure: %s\n", q.URL, err.Error())
continue
}

View File

@ -6,6 +6,7 @@ import (
"net/http"
"qurl/static"
"qurl/storage"
"qurl/qurl"
)
type RootHandler struct {
@ -39,7 +40,19 @@ func (ctx *RootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx.ServeAPI(w, r)
default:
fmt.Printf("Path: %s\n", fname)
id, err := qurl.FromString(fname[1:len(fname)])
if err != nil {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
q, err := ctx.Storage.GetQURLByID(id)
if err != nil {
http.Error(w, fmt.Sprintf("Database error: %s", err.Error()),
http.StatusInternalServerError)
return
}
http.Redirect(w, r, q.URL, http.StatusPermanentRedirect)
}
}

View File

@ -158,3 +158,34 @@ func (stor *BoltStorage) GetQURLByURL(u string) (*qurl.QURL, error) {
return q, nil
}
func (stor *BoltStorage) GetQURLByID(id uint64) (*qurl.QURL, error) {
tx, err := stor.DB.Begin(false)
if err != nil {
return nil, err
}
defer tx.Rollback()
// Create a byte array from the ID
bid := make([]byte, 8)
binary.BigEndian.PutUint64(bid, id)
rb := tx.Bucket(QURLBucket)
if rb == nil {
return nil, nil
}
qb := rb.Bucket(bid)
if qb == nil {
return nil, nil
}
q := &qurl.QURL{ID: id}
qu := qb.Get(URLField)
if qu != nil {
q.URL = string(qu)
}
return q, nil
}

View File

@ -11,6 +11,7 @@ import (
type Storage interface {
AddQURL(*qurl.QURL) error
GetQURLByURL(string) (*qurl.QURL, error)
GetQURLByID(uint64) (*qurl.QURL, error)
SetQURLSequence(uint64) error
Backup(string) error
Shutdown()