1
0
mirror of https://github.com/mgerb/go-discord-bot synced 2026-01-11 01:22:48 +00:00

convert to chi web framework - add tls support

This commit is contained in:
2017-07-20 21:34:36 -05:00
parent b915ec065a
commit 4baad6b025
6 changed files with 178 additions and 62 deletions

View File

@@ -2,48 +2,91 @@ package webserver
import (
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/buaazp/fasthttprouter"
"golang.org/x/crypto/acme/autocert"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/mgerb/go-discord-bot/server/config"
"github.com/mgerb/go-discord-bot/server/webserver/handlers"
"github.com/valyala/fasthttp"
)
func logger(next fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
logger := ctx.Logger()
logger.Printf(ctx.RemoteAddr().String())
next(ctx)
}
}
func applyMiddleware(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
newHandler := logger(handler)
return newHandler
}
func registerRoutes(router *fasthttprouter.Router) {
router.GET("/soundlist", handlers.SoundList)
router.PUT("/upload", handlers.FileUpload)
router.ServeFiles("/static/*filepath", "./dist/static")
router.ServeFiles("/sounds/*filepath", config.Config.SoundsPath)
router.NotFound = func(ctx *fasthttp.RequestCtx) {
fasthttp.ServeFile(ctx, "./dist/index.html")
func getRouter() *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.DefaultCompress)
if !config.Flags.Prod {
r.Use(middleware.Logger)
}
r.Get("/soundlist", handlers.SoundList)
r.Put("/upload", handlers.FileUpload)
workDir, _ := os.Getwd()
FileServer(r, "/static", http.Dir(filepath.Join(workDir, "./dist/static")))
FileServer(r, "/sounds", http.Dir(filepath.Join(workDir, "./sounds")))
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./dist/index.html")
})
return r
}
// Start -
func Start() {
router := fasthttprouter.New()
router := getRouter()
registerRoutes(router)
if config.Flags.TLS {
// apply our middleware
handlers := applyMiddleware(router.Handler)
// start server on port 80 to redirect
go http.ListenAndServe(":80", http.HandlerFunc(redirect))
// start web server
log.Fatal(fasthttp.ListenAndServe(config.Config.ServerAddr, handlers))
// start TLS server
log.Fatal(http.Serve(autocert.NewListener(), router))
} else {
// start basic server
http.ListenAndServe(config.Config.ServerAddr, router)
}
}
// FileServer conveniently sets up a http.FileServer handler to serve
// static files from a http.FileSystem.
func FileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters.")
}
fs := http.StripPrefix(path, http.FileServer(root))
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
}))
}
// redirect to https
func redirect(w http.ResponseWriter, req *http.Request) {
// remove/add not default ports from req.Host
target := "https://" + req.Host + req.URL.Path
if len(req.URL.RawQuery) > 0 {
target += "?" + req.URL.RawQuery
}
http.Redirect(w, req, target, http.StatusTemporaryRedirect)
}