yatwiki/WikiServer.go

96 lines
2.2 KiB
Go
Raw Normal View History

2017-07-08 23:13:36 +00:00
package yatwiki3
import (
"errors"
2017-07-08 23:13:36 +00:00
"html/template"
"net/http"
"net/url"
2017-07-09 01:18:18 +00:00
"strconv"
"strings"
2017-07-08 23:13:36 +00:00
)
type WikiServer struct {
db *WikiDB
opts *ServerOptions
pageTmp *template.Template
}
func NewWikiServer(opts *ServerOptions) (*WikiServer, error) {
wdb, err := NewWikiDB(opts.DBFilePath)
if err != nil {
return nil, err
}
tmpl, err := template.New("yatwiki/page").Parse(pageTemplate)
if err != nil {
panic(err)
}
ws := WikiServer{
db: wdb,
opts: opts,
pageTmp: tmpl,
}
return &ws, nil
}
func (this *WikiServer) Close() {
this.db.Close()
}
func (this *WikiServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "YATWiki3")
2017-07-08 23:13:36 +00:00
if r.Method == "GET" {
if r.URL.Path == this.opts.ExpectBaseURL+"wiki.css" {
w.Header().Set("Content-Type", "text/css")
content, _ := wikiCssBytes()
w.Write(content)
return
} else if r.URL.Path == this.opts.ExpectBaseURL+"highlight.js" {
w.Header().Set("Content-Type", "application/javascript")
content, _ := highlightJsBytes()
w.Write(content)
return
2017-07-09 00:14:28 +00:00
} else if r.URL.Path == this.opts.ExpectBaseURL+"favicon.ico" && len(this.opts.FaviconFilePath) > 0 {
w.Header().Set("Content-Type", "image/x-icon")
http.ServeFile(w, r, this.opts.FaviconFilePath)
return
} else if r.URL.Path == this.opts.ExpectBaseURL+"formatting" {
this.routeFormatting(w, r)
return
} else if r.URL.Path == this.opts.ExpectBaseURL+"index" {
this.routeIndex(w, r)
return
} else if strings.HasPrefix(r.URL.Path, this.opts.ExpectBaseURL+"view/") {
articleTitle, err := url.QueryUnescape(r.URL.Path[len(this.opts.ExpectBaseURL+"view/"):])
if err != nil {
this.serveErrorMessage(w, err)
return
}
this.routeView(w, r, articleTitle)
return
2017-07-09 01:18:18 +00:00
} else if strings.HasPrefix(r.URL.Path, this.opts.ExpectBaseURL+"raw/") {
revId, err := strconv.Atoi(r.URL.Path[len(this.opts.ExpectBaseURL+"raw/"):])
if err != nil {
this.serveErrorMessage(w, err)
return
}
this.routeRawView(w, r, revId)
2017-07-09 01:18:18 +00:00
return
}
}
// No match? Add 'Page not found' to next session response, and redirect to homepage
this.serveErrorMessage(w, errors.New("Page not found"))
}