GoBlog/regexRedirects.go

47 lines
880 B
Go
Raw Normal View History

2020-10-15 18:54:43 +00:00
package main
import (
"net/http"
"regexp"
)
var regexRedirects []*regexRedirect
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
}
2020-10-15 19:12:28 +00:00
func initRegexRedirects() error {
2020-10-15 18:54:43 +00:00
for _, cr := range appConfig.PathRedirects {
re, err := regexp.Compile(cr.From)
if err != nil {
return err
}
r := &regexRedirect{
2020-10-15 18:54:43 +00:00
From: re,
To: cr.To,
2020-11-10 06:53:08 +00:00
Type: cr.Type,
}
if r.Type == 0 {
r.Type = http.StatusFound
}
regexRedirects = append(regexRedirects, r)
2020-10-15 18:54:43 +00:00
}
return nil
}
func checkRegexRedirects(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, re := range regexRedirects {
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
http.Redirect(w, r, r.URL.String(), re.Type)
2020-10-15 18:54:43 +00:00
return
}
}
next.ServeHTTP(w, r)
})
}