2020-10-15 18:54:43 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"regexp"
|
|
|
|
)
|
|
|
|
|
|
|
|
type regexRedirect struct {
|
|
|
|
From *regexp.Regexp
|
|
|
|
To string
|
2020-11-10 06:53:08 +00:00
|
|
|
Type int
|
2020-10-15 18:54:43 +00:00
|
|
|
}
|
|
|
|
|
2021-06-06 12:39:42 +00:00
|
|
|
func (a *goBlog) initRegexRedirects() error {
|
|
|
|
for _, cr := range a.cfg.PathRedirects {
|
2020-10-15 18:54:43 +00:00
|
|
|
re, err := regexp.Compile(cr.From)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-21 16:08:11 +00:00
|
|
|
r := ®exRedirect{
|
2020-10-15 18:54:43 +00:00
|
|
|
From: re,
|
|
|
|
To: cr.To,
|
2020-11-10 06:53:08 +00:00
|
|
|
Type: cr.Type,
|
2021-01-21 16:08:11 +00:00
|
|
|
}
|
|
|
|
if r.Type == 0 {
|
|
|
|
r.Type = http.StatusFound
|
|
|
|
}
|
2021-06-06 12:39:42 +00:00
|
|
|
a.regexRedirects = append(a.regexRedirects, r)
|
2020-10-15 18:54:43 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-06-06 12:39:42 +00:00
|
|
|
func (a *goBlog) checkRegexRedirects(next http.Handler) http.Handler {
|
2020-10-15 18:54:43 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2021-06-06 12:39:42 +00:00
|
|
|
for _, re := range a.regexRedirects {
|
2021-01-21 16:08:11 +00:00
|
|
|
if newPath := re.From.ReplaceAllString(r.URL.Path, re.To); r.URL.Path != newPath {
|
2020-10-15 18:54:43 +00:00
|
|
|
r.URL.Path = newPath
|
2021-01-21 16:08:11 +00:00
|
|
|
http.Redirect(w, r, r.URL.String(), re.Type)
|
2020-10-15 18:54:43 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|