From 6fdab4be3477a5eedb2d3dd6ddf8b0255b0167e0 Mon Sep 17 00:00:00 2001 From: handlerug Date: Fri, 16 Jul 2021 00:46:35 +0700 Subject: [PATCH] Migrate to gorilla/mux for web needs What a wonderful package! --- cfg/config.go | 26 ++++++++++++------------- go.mod | 1 + go.sum | 2 ++ httpd.go | 4 ++-- main.go | 4 +--- user/net.go | 10 +++++----- user/user.go | 4 ++-- web/admin.go | 14 ++++++++------ web/auth.go | 24 +++++++++++++----------- web/history.go | 15 +++++++++------ web/mutators.go | 22 ++++++++++++---------- web/readers.go | 22 ++++++++++++---------- web/search.go | 15 ++++++++------- web/stuff.go | 26 +++++++++++++------------ web/web.go | 50 +++++++++++++++++++++++++++++++++---------------- 15 files changed, 136 insertions(+), 103 deletions(-) diff --git a/cfg/config.go b/cfg/config.go index ec55c4f..45f910f 100644 --- a/cfg/config.go +++ b/cfg/config.go @@ -30,17 +30,17 @@ var ( AllowRegistration bool RegistrationLimit uint64 Locked bool - UseWhiteList bool - WhiteList []string + UseWhiteList bool + WhiteList []string CommonScripts []string ViewScripts []string EditScripts []string // TelegramEnabled if both TelegramBotToken and TelegramBotName are not empty strings. - TelegramEnabled bool + TelegramEnabled bool TelegramBotToken string - TelegramBotName string + TelegramBotName string ) // WikiDir is a full path to the wiki storage directory, which also must be a @@ -56,7 +56,7 @@ type Config struct { Network Authorization CustomScripts `comment:"You can specify additional scripts to load on different kinds of pages, delimited by a comma ',' sign."` - Telegram `comment:"You can enable Telegram authorization. Follow these instructions: https://core.telegram.org/widgets/login#setting-up-a-bot"` + Telegram `comment:"You can enable Telegram authorization. Follow these instructions: https://core.telegram.org/widgets/login#setting-up-a-bot"` } // Hyphae is a section of Config which has fields related to special hyphae. @@ -89,16 +89,16 @@ type CustomScripts struct { type Authorization struct { UseAuth bool AllowRegistration bool - RegistrationLimit uint64 `comment:"This field controls the maximum amount of allowed registrations."` - Locked bool `comment:"Set if users have to authorize to see anything on the wiki."` - UseWhiteList bool `comment:"If true, WhiteList is used. Else it is not used."` - WhiteList []string `delim:"," comment:"Usernames of people who can log in to your wiki separated by comma."` + RegistrationLimit uint64 `comment:"This field controls the maximum amount of allowed registrations."` + Locked bool `comment:"Set if users have to authorize to see anything on the wiki."` + UseWhiteList bool `comment:"If true, WhiteList is used. Else it is not used."` + WhiteList []string `delim:"," comment:"Usernames of people who can log in to your wiki separated by comma."` } // Telegram is the section of Config that sets Telegram authorization. type Telegram struct { TelegramBotToken string `comment:"Token of your bot.` - TelegramBotName string `comment:"Username of your bot, sans @.` + TelegramBotName string `comment:"Username of your bot, sans @.` } // ReadConfigFile reads a config on the given path and stores the @@ -121,8 +121,8 @@ func ReadConfigFile(path string) error { AllowRegistration: false, RegistrationLimit: 0, Locked: false, - UseWhiteList: false, - WhiteList: []string{}, + UseWhiteList: false, + WhiteList: []string{}, }, CustomScripts: CustomScripts{ CommonScripts: []string{}, @@ -131,7 +131,7 @@ func ReadConfigFile(path string) error { }, Telegram: Telegram{ TelegramBotToken: "", - TelegramBotName: "", + TelegramBotName: "", }, } diff --git a/go.mod b/go.mod index a2fa08a..8d5b338 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/bouncepaw/mycomarkup v0.5.8 github.com/go-ini/ini v1.62.0 github.com/gorilla/feeds v1.1.1 + github.com/gorilla/mux v1.8.0 github.com/kr/pretty v0.2.1 // indirect github.com/smartystreets/goconvey v1.6.4 // indirect github.com/valyala/quicktemplate v1.6.3 diff --git a/go.sum b/go.sum index 16a458f..33434bc 100644 --- a/go.sum +++ b/go.sum @@ -7,6 +7,8 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGa github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/feeds v1.1.1 h1:HwKXxqzcRNg9to+BbvJog4+f3s/xzvtZXICcQGutYfY= github.com/gorilla/feeds v1.1.1/go.mod h1:Nk0jZrvPFZX1OBe5NPiddPw7CfwF6Q9eqzaBbaightA= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= diff --git a/httpd.go b/httpd.go index dcaab4d..7ee56e7 100644 --- a/httpd.go +++ b/httpd.go @@ -11,12 +11,12 @@ import ( "github.com/bouncepaw/mycorrhiza/cfg" ) -func serveHTTP() { +func serveHTTP(handler http.Handler) { server := &http.Server{ ReadTimeout: 300 * time.Second, WriteTimeout: 300 * time.Second, IdleTimeout: 300 * time.Second, - Handler: http.DefaultServeMux, + Handler: handler, } if strings.HasPrefix(cfg.ListenAddr, "/") { diff --git a/main.go b/main.go index 46b3f8a..e16230b 100644 --- a/main.go +++ b/main.go @@ -45,7 +45,5 @@ func main() { // Static files: static.InitFS(files.StaticFiles()) - // Network: - web.Init() - serveHTTP() + serveHTTP(web.Handler()) } diff --git a/user/net.go b/user/net.go index fdbfcce..45da976 100644 --- a/user/net.go +++ b/user/net.go @@ -1,15 +1,15 @@ package user import ( - "fmt" - "log" - "net/http" - "time" "crypto/hmac" "crypto/sha256" "encoding/hex" + "fmt" + "log" + "net/http" "sort" "strings" + "time" "github.com/bouncepaw/mycorrhiza/cfg" "github.com/bouncepaw/mycorrhiza/util" @@ -64,7 +64,7 @@ func Register(username, password, group, source string, force bool) error { u := User{ Name: username, Group: group, - Source: source, + Source: source, Password: string(hash), RegisteredAt: time.Now(), } diff --git a/user/user.go b/user/user.go index a2e554d..966916e 100644 --- a/user/user.go +++ b/user/user.go @@ -17,7 +17,7 @@ type User struct { Password string `json:"hashed_password"` RegisteredAt time.Time `json:"registered_on"` // Source is where the user from. Valid values: valid, telegram. - Source string `json:"source"` + Source string `json:"source"` sync.RWMutex // A note about why HashedPassword is string and not []byte. The reason is @@ -77,7 +77,7 @@ func EmptyUser() *User { Name: "anon", Group: "anon", Password: "", - Source: "local", + Source: "local", } } diff --git a/web/admin.go b/web/admin.go index f118cae..18dc00d 100644 --- a/web/admin.go +++ b/web/admin.go @@ -9,6 +9,8 @@ import ( "sort" "strings" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/cfg" "github.com/bouncepaw/mycorrhiza/user" "github.com/bouncepaw/mycorrhiza/util" @@ -16,14 +18,14 @@ import ( ) // initAdmin sets up /admin routes if auth is used. Call it after you have decided if you want to use auth. -func initAdmin() { +func initAdmin(r *mux.Router) { if cfg.UseAuth { - http.HandleFunc("/admin/", handlerAdmin) - http.HandleFunc("/admin/shutdown/", handlerAdminShutdown) - http.HandleFunc("/admin/reindex-users/", handlerAdminReindexUsers) + r.HandleFunc("/admin/shutdown", handlerAdminShutdown) + r.HandleFunc("/admin/reindex-users", handlerAdminReindexUsers) - http.HandleFunc("/admin/users/", handlerAdminUsers) - http.HandleFunc("/admin/user/new", handlerAdminUserNew) + r.PathPrefix("/admin/users/").HandlerFunc(handlerAdminUsers) + r.HandleFunc("/admin/user/new", handlerAdminUserNew) + r.HandleFunc("/admin", handlerAdmin) } } diff --git a/web/auth.go b/web/auth.go index eef0f7f..5a7ea16 100644 --- a/web/auth.go +++ b/web/auth.go @@ -9,27 +9,29 @@ import ( "net/http" "strings" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/cfg" "github.com/bouncepaw/mycorrhiza/user" "github.com/bouncepaw/mycorrhiza/util" "github.com/bouncepaw/mycorrhiza/views" ) -func initAuth() { - http.HandleFunc("/lock", handlerLock) +func initAuth(r *mux.Router) { + r.HandleFunc("/lock", handlerLock) if !cfg.UseAuth { return } if cfg.AllowRegistration { - http.HandleFunc("/register", handlerRegister) + r.HandleFunc("/register", handlerRegister) } if cfg.TelegramEnabled { - http.HandleFunc("/telegram-login", handlerTelegramLogin) + r.HandleFunc("/telegram-login", handlerTelegramLogin) } - http.HandleFunc("/login", handlerLogin) - http.HandleFunc("/login-data", handlerLoginData) - http.HandleFunc("/logout", handlerLogout) - http.HandleFunc("/logout-confirm", handlerLogoutConfirm) + r.HandleFunc("/login", handlerLogin) + r.HandleFunc("/login-data", handlerLoginData) + r.HandleFunc("/logout", handlerLogout) + r.HandleFunc("/logout-confirm", handlerLogoutConfirm) } func handlerLock(w http.ResponseWriter, rq *http.Request) { @@ -128,10 +130,10 @@ func handlerTelegramLogin(w http.ResponseWriter, rq *http.Request) { w.Header().Set("Content-Type", "text/html;charset=utf-8") rq.ParseForm() var ( - values = rq.URL.Query() - username = strings.ToLower(values.Get("username")) + values = rq.URL.Query() + username = strings.ToLower(values.Get("username")) seemsValid = user.TelegramAuthParamsAreValid(values) - err = user.Register( + err = user.Register( username, "", // Password matters not "editor", diff --git a/web/history.go b/web/history.go index eb5e2f8..5bb77dc 100644 --- a/web/history.go +++ b/web/history.go @@ -7,18 +7,21 @@ import ( "strconv" "strings" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/history" "github.com/bouncepaw/mycorrhiza/user" "github.com/bouncepaw/mycorrhiza/util" "github.com/bouncepaw/mycorrhiza/views" ) -func initHistory() { - http.HandleFunc("/history/", handlerHistory) - http.HandleFunc("/recent-changes/", handlerRecentChanges) - http.HandleFunc("/recent-changes-rss", handlerRecentChangesRSS) - http.HandleFunc("/recent-changes-atom", handlerRecentChangesAtom) - http.HandleFunc("/recent-changes-json", handlerRecentChangesJSON) +func initHistory(r *mux.Router) { + r.PathPrefix("/history/").HandlerFunc(handlerHistory) + + r.PathPrefix("/recent-changes/").HandlerFunc(handlerRecentChanges) + r.HandleFunc("/recent-changes-rss", handlerRecentChangesRSS) + r.HandleFunc("/recent-changes-atom", handlerRecentChangesAtom) + r.HandleFunc("/recent-changes-json", handlerRecentChangesJSON) } // handlerHistory lists all revisions of a hypha. diff --git a/web/mutators.go b/web/mutators.go index a850e66..3f507ed 100644 --- a/web/mutators.go +++ b/web/mutators.go @@ -7,6 +7,8 @@ import ( "log" "net/http" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/history" "github.com/bouncepaw/mycorrhiza/hyphae" "github.com/bouncepaw/mycorrhiza/shroom" @@ -15,18 +17,18 @@ import ( "github.com/bouncepaw/mycorrhiza/views" ) -func initMutators() { +func initMutators(r *mux.Router) { // Those that do not actually mutate anything: - http.HandleFunc("/edit/", handlerEdit) - http.HandleFunc("/delete-ask/", handlerDeleteAsk) - http.HandleFunc("/rename-ask/", handlerRenameAsk) - http.HandleFunc("/unattach-ask/", handlerUnattachAsk) + r.PathPrefix("/edit/").HandlerFunc(handlerEdit) + r.PathPrefix("/delete-ask/").HandlerFunc(handlerDeleteAsk) + r.PathPrefix("/rename-ask/").HandlerFunc(handlerRenameAsk) + r.PathPrefix("/unattach-ask/").HandlerFunc(handlerUnattachAsk) // And those that do mutate something: - http.HandleFunc("/upload-binary/", handlerUploadBinary) - http.HandleFunc("/upload-text/", handlerUploadText) - http.HandleFunc("/delete-confirm/", handlerDeleteConfirm) - http.HandleFunc("/rename-confirm/", handlerRenameConfirm) - http.HandleFunc("/unattach-confirm/", handlerUnattachConfirm) + r.PathPrefix("/upload-binary/").HandlerFunc(handlerUploadBinary) + r.PathPrefix("/upload-text/").HandlerFunc(handlerUploadText) + r.PathPrefix("/delete-confirm/").HandlerFunc(handlerDeleteConfirm) + r.PathPrefix("/rename-confirm/").HandlerFunc(handlerRenameConfirm) + r.PathPrefix("/unattach-confirm/").HandlerFunc(handlerUnattachConfirm) } func factoryHandlerAsker( diff --git a/web/readers.go b/web/readers.go index 61f1868..0e2bf4a 100644 --- a/web/readers.go +++ b/web/readers.go @@ -2,14 +2,14 @@ package web import ( "fmt" - "github.com/bouncepaw/mycomarkup/mycocontext" - "github.com/bouncepaw/mycorrhiza/cfg" "log" "net/http" "os" "path/filepath" "strings" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/history" "github.com/bouncepaw/mycorrhiza/hyphae" "github.com/bouncepaw/mycorrhiza/mimetype" @@ -18,16 +18,18 @@ import ( "github.com/bouncepaw/mycorrhiza/views" "github.com/bouncepaw/mycomarkup" + "github.com/bouncepaw/mycomarkup/mycocontext" + "github.com/bouncepaw/mycorrhiza/cfg" ) -func initReaders() { - http.HandleFunc("/page/", handlerHypha) - http.HandleFunc("/hypha/", handlerHypha) - http.HandleFunc("/text/", handlerText) - http.HandleFunc("/binary/", handlerBinary) - http.HandleFunc("/rev/", handlerRevision) - http.HandleFunc("/primitive-diff/", handlerPrimitiveDiff) - http.HandleFunc("/attachment/", handlerAttachment) +func initReaders(r *mux.Router) { + r.PathPrefix("/page/").HandlerFunc(handlerHypha) + r.PathPrefix("/hypha/").HandlerFunc(handlerHypha) + r.PathPrefix("/text/").HandlerFunc(handlerText) + r.PathPrefix("/binary/").HandlerFunc(handlerBinary) + r.PathPrefix("/rev/").HandlerFunc(handlerRevision) + r.PathPrefix("/primitive-diff/").HandlerFunc(handlerPrimitiveDiff) + r.PathPrefix("/attachment/").HandlerFunc(handlerAttachment) } func handlerAttachment(w http.ResponseWriter, rq *http.Request) { diff --git a/web/search.go b/web/search.go index 3325af2..81df445 100644 --- a/web/search.go +++ b/web/search.go @@ -1,19 +1,20 @@ package web import ( - "github.com/bouncepaw/mycorrhiza/shroom" - "github.com/bouncepaw/mycorrhiza/user" - "github.com/bouncepaw/mycorrhiza/views" "io" "net/http" + "github.com/gorilla/mux" + + "github.com/bouncepaw/mycorrhiza/shroom" + "github.com/bouncepaw/mycorrhiza/user" "github.com/bouncepaw/mycorrhiza/util" + "github.com/bouncepaw/mycorrhiza/views" ) -func initSearch() { - http.HandleFunc("/title-search/", handlerTitleSearch) - http.HandleFunc("/title-search-json/", handlerTitleSearchJSON) // we get a little shroomy - +func initSearch(r *mux.Router) { + r.PathPrefix("/title-search/").HandlerFunc(handlerTitleSearch) + r.PathPrefix("/title-search-json/").HandlerFunc(handlerTitleSearchJSON) } func handlerTitleSearch(w http.ResponseWriter, rq *http.Request) { diff --git a/web/stuff.go b/web/stuff.go index a914ea5..b393861 100644 --- a/web/stuff.go +++ b/web/stuff.go @@ -2,33 +2,35 @@ package web // stuff.go is used for meta stuff about the wiki or all hyphae at once. import ( - "github.com/bouncepaw/mycomarkup" - "github.com/bouncepaw/mycomarkup/mycocontext" - "github.com/bouncepaw/mycorrhiza/help" "io" "log" "math/rand" "net/http" "strings" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/cfg" "github.com/bouncepaw/mycorrhiza/files" - + "github.com/bouncepaw/mycorrhiza/help" "github.com/bouncepaw/mycorrhiza/hyphae" "github.com/bouncepaw/mycorrhiza/shroom" "github.com/bouncepaw/mycorrhiza/user" "github.com/bouncepaw/mycorrhiza/util" "github.com/bouncepaw/mycorrhiza/views" + + "github.com/bouncepaw/mycomarkup" + "github.com/bouncepaw/mycomarkup/mycocontext" ) -func initStuff() { - http.HandleFunc("/help/", handlerHelp) - http.HandleFunc("/list/", handlerList) - http.HandleFunc("/reindex/", handlerReindex) - http.HandleFunc("/update-header-links/", handlerUpdateHeaderLinks) - http.HandleFunc("/random/", handlerRandom) - http.HandleFunc("/about/", handlerAbout) - http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, rq *http.Request) { +func initStuff(r *mux.Router) { + r.PathPrefix("/help/").HandlerFunc(handlerHelp) + r.HandleFunc("/list", handlerList) + r.HandleFunc("/reindex", handlerReindex) + r.HandleFunc("/update-header-links", handlerUpdateHeaderLinks) + r.HandleFunc("/random", handlerRandom) + r.HandleFunc("/about", handlerAbout) + r.HandleFunc("/favicon.ico", func(w http.ResponseWriter, rq *http.Request) { http.Redirect(w, rq, "/static/favicon.ico", http.StatusSeeOther) }) } diff --git a/web/web.go b/web/web.go index 05bb4a9..4ab91f3 100644 --- a/web/web.go +++ b/web/web.go @@ -11,6 +11,8 @@ import ( "net/http" "net/url" + "github.com/gorilla/mux" + "github.com/bouncepaw/mycorrhiza/cfg" "github.com/bouncepaw/mycorrhiza/static" "github.com/bouncepaw/mycorrhiza/user" @@ -73,27 +75,43 @@ func handlerRobotsTxt(w http.ResponseWriter, rq *http.Request) { file.Close() } -func Init() { - initAdmin() - initReaders() - initMutators() - initAuth() - initHistory() - initStuff() - initSearch() +func Handler() http.Handler { + r := mux.NewRouter() + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Do stuff here + log.Println(r.RequestURI) + // Call the next handler, which can be another middleware in the chain, or the final handler. + next.ServeHTTP(w, r) + }) + }) + + // Available all the time + initAuth(r) + + initReaders(r) + initMutators(r) + + initAdmin(r) + initHistory(r) + initStuff(r) + initSearch(r) // Miscellaneous - http.HandleFunc("/user-list/", handlerUserList) - http.HandleFunc("/robots.txt", handlerRobotsTxt) + r.HandleFunc("/user-list", handlerUserList) + r.HandleFunc("/robots.txt", handlerRobotsTxt) // Static assets - http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(static.FS)))) - http.HandleFunc("/static/style.css", handlerStyle) + r.HandleFunc("/static/style.css", handlerStyle) + r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.FS(static.FS)))) // Index page - http.HandleFunc("/", func(w http.ResponseWriter, rq *http.Request) { - addr, _ := url.Parse("/hypha/" + cfg.HomeHypha) // Let's pray it never fails - rq.URL = addr - handlerHypha(w, rq) + r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + // Let's pray it never fails + addr, _ := url.Parse("/hypha/" + cfg.HomeHypha) + r.URL = addr + handlerHypha(w, r) }) + + return r }