make route handling better

This commit is contained in:
hcl
2021-01-25 23:28:52 +08:00
committed by nkanaev
parent 4f79c919f0
commit 52073e7e81
4 changed files with 40 additions and 54 deletions

View File

@@ -2,12 +2,14 @@ package server
import (
"context"
"github.com/nkanaev/yarr/storage"
"log"
"net/http"
"runtime"
"strings"
"sync/atomic"
"time"
"github.com/nkanaev/yarr/storage"
)
type Handler struct {
@@ -18,11 +20,11 @@ type Handler struct {
queueSize *int32
refreshRate chan int64
// auth
Username string
Password string
Username string
Password string
// https
CertFile string
KeyFile string
CertFile string
KeyFile string
}
func New(db *storage.Storage, logger *log.Logger, addr string) *Handler {
@@ -39,7 +41,7 @@ func New(db *storage.Storage, logger *log.Logger, addr string) *Handler {
func (h *Handler) GetAddr() string {
proto := "http"
if (h.CertFile != "" && h.KeyFile != "") {
if h.CertFile != "" && h.KeyFile != "" {
proto = "https"
}
return proto + "://" + h.Addr
@@ -65,7 +67,15 @@ func unsafeMethod(method string) bool {
}
func (h Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
route, vars := getRoute(req)
reqPath := req.URL.Path
if BasePath != "" {
reqPath = strings.TrimPrefix(req.URL.Path, BasePath)
if reqPath == "" {
http.Redirect(rw, req, BasePath+"/", http.StatusFound)
return
}
}
route, vars := getRoute(reqPath)
if route == nil {
rw.WriteHeader(http.StatusNotFound)
return