move url helpers to reusable struct

This commit is contained in:
mappu 2017-08-13 15:51:32 +12:00
parent 9e070d269b
commit 5c26ff75aa
2 changed files with 45 additions and 28 deletions

View File

@ -121,48 +121,37 @@ func (this *ArchiveServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
func (this *ArchiveServer) legacyRoute(w http.ResponseWriter, r *http.Request) { func (this *ArchiveServer) legacyRoute(w http.ResponseWriter, r *http.Request) {
u := URLHelper{w, r}
intval := func(sz string) int { hubid := 0
ret, _ := strconv.Atoi(sz) if u.hasGet("h") {
return ret hubid = u.intval(u.get("h"))
}
get := r.URL.Query().Get
hasGet := func(sz string) bool {
return len(get(sz)) > 0
}
redirectf := func(format string, a ...interface{}) {
http.Redirect(w, r, fmt.Sprintf(format, a...), http.StatusTemporaryRedirect)
} }
// //
hubid := 0 if u.hasGet("q") {
if hasGet("h") { if u.hasGet("rx") {
hubid = intval(get("h")) u.redirectf(`/%d/rx/%s`, hubid, url.QueryEscape(u.get("q")))
}
if hasGet("q") {
if hasGet("rx") {
redirectf(`/%d/rx/%s`, hubid, url.QueryEscape(get("q")))
} else { } else {
redirectf(`/%d/search/%s`, hubid, url.QueryEscape(get("q"))) u.redirectf(`/%d/search/%s`, hubid, url.QueryEscape(u.get("q")))
} }
} else if hasGet("y") && hasGet("m") { } else if u.hasGet("y") && u.hasGet("m") {
year := intval(get("y")) year := u.intval(u.get("y"))
month := intval(get("m")) month := u.intval(u.get("m"))
if hasGet("p") { if u.hasGet("p") {
redirectf(`/%d/%d/%d/page-%d`, hubid, year, month, intval(get("p"))) u.redirectf(`/%d/%d/%d/page-%d`, hubid, year, month, u.intval(u.get("p")))
} else { } else {
redirectf(`/%d/%d/%d`, hubid, year, month) u.redirectf(`/%d/%d/%d`, hubid, year, month)
} }
} else { } else {
if hi := this.lookupSourceByNumericString(get("h")); hi != nil { if hi := this.lookupSourceByNumericString(u.get("h")); hi != nil {
currentDate := hi.LatestDate() currentDate := hi.LatestDate()
redirectf(`/%d/%d/%d`, hubid, currentDate.Year, currentDate.Month) u.redirectf(`/%d/%d/%d`, hubid, currentDate.Year, currentDate.Month)
} else { } else {
redirectf(`/`) u.redirectf(`/`)
} }
} }

28
util.go
View File

@ -1,5 +1,11 @@
package archive package archive
import (
"fmt"
"net/http"
"strconv"
)
func attr(condition bool, whenMet string) string { func attr(condition bool, whenMet string) string {
if condition { if condition {
return whenMet return whenMet
@ -7,3 +13,25 @@ func attr(condition bool, whenMet string) string {
return "" return ""
} }
} }
type URLHelper struct {
w http.ResponseWriter
r *http.Request
}
func (this *URLHelper) intval(sz string) int {
ret, _ := strconv.Atoi(sz)
return ret
}
func (this *URLHelper) get(sz string) string {
return this.r.URL.Query().Get(sz)
}
func (this *URLHelper) hasGet(sz string) bool {
return len(this.r.URL.Query().Get(sz)) > 0
}
func (this *URLHelper) redirectf(format string, a ...interface{}) {
http.Redirect(this.w, this.r, fmt.Sprintf(format, a...), http.StatusTemporaryRedirect)
}