rewrite diff endpoint to nice URL

This commit is contained in:
mappu 2017-07-11 18:31:50 +12:00
parent f560430efe
commit 6ba86ca170

View File

@ -6,6 +6,7 @@ import (
"html/template" "html/template"
"net/http" "net/http"
"net/url" "net/url"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -16,6 +17,7 @@ type WikiServer struct {
opts *ServerOptions opts *ServerOptions
pageTmp *template.Template pageTmp *template.Template
loc *time.Location loc *time.Location
rxDiff *regexp.Regexp
} }
func NewWikiServer(opts *ServerOptions) (*WikiServer, error) { func NewWikiServer(opts *ServerOptions) (*WikiServer, error) {
@ -39,6 +41,7 @@ func NewWikiServer(opts *ServerOptions) (*WikiServer, error) {
opts: opts, opts: opts,
pageTmp: tmpl, pageTmp: tmpl,
loc: loc, loc: loc,
rxDiff: regexp.MustCompile(`diff/(\d+)/(\d+)`),
} }
return &ws, nil return &ws, nil
} }
@ -50,6 +53,11 @@ func (this *WikiServer) Close() {
func (this *WikiServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (this *WikiServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "YATWiki3") w.Header().Set("Server", "YATWiki3")
if !strings.HasPrefix(r.URL.Path, this.opts.ExpectBaseURL) {
http.Error(w, "Bad request", 400)
return
}
if r.Method == "GET" { if r.Method == "GET" {
if r.URL.Path == this.opts.ExpectBaseURL+"wiki.css" { if r.URL.Path == this.opts.ExpectBaseURL+"wiki.css" {
w.Header().Set("Content-Type", "text/css") w.Header().Set("Content-Type", "text/css")
@ -140,14 +148,18 @@ func (this *WikiServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} else if r.URL.Path == this.opts.ExpectBaseURL+"diff" { } else if r.URL.Path == this.opts.ExpectBaseURL+"diff" {
this.serveRedirect(w, this.opts.ExpectBaseURL+`diff/`+r.URL.Query().Get("f")+`/`+r.URL.Query().Get("t"))
return
fromRev, err := strconv.Atoi(r.URL.Query().Get("f")) } else if match := this.rxDiff.FindStringSubmatch(r.URL.Path[len(this.opts.ExpectBaseURL):]); len(match) == 3 {
fromRev, err := strconv.Atoi(match[1])
if err != nil { if err != nil {
this.serveErrorMessage(w, err) this.serveErrorMessage(w, err)
return return
} }
toRev, err := strconv.Atoi(r.URL.Query().Get("t")) toRev, err := strconv.Atoi(match[2])
if err != nil { if err != nil {
this.serveErrorMessage(w, err) this.serveErrorMessage(w, err)
return return