Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.4 KiB

package wrouter
import (
"fmt"
"net/http"
"strings"
"time"
"git.aiterp.net/gisle/wrouter/auth"
)
type Route interface {
Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool
}
type Router struct {
paths map[Route]string
routes []Route
}
func (router *Router) Route(path string, route Route) {
if router.paths == nil {
router.paths = make(map[Route]string, 16)
}
router.paths[route] = path
router.routes = append(router.routes, route)
}
func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
defer req.Body.Close()
// Allow REST for clients of yore
if req.Header.Get("X-Method") != "" {
req.Method = strings.ToUpper(req.Header.Get("X-Method"))
}
// Resolve session cookies
var user *auth.User
var sess *auth.Session
cookie, err := req.Cookie(auth.SessionCookieName)
if cookie != nil && err == nil {
sess = auth.FindSession(cookie.Value)
if sess != nil {
user, _ = auth.FindUser(sess.UserID)
}
}
for index, route := range router.routes {
path := router.paths[route]
if strings.HasPrefix(strings.ToLower(req.URL.Path), path) {
// Just so the handler can replace the path properly in case of case
// insensitive clients getting fancy on it.
path = req.URL.Path[:len(path)]
// Attach a little something for testing
w.Header().Set("X-Route-Path", path)
w.Header().Set("X-Route-Index", fmt.Sprint(index))
if route.Handle(path, w, req, user) {
if user != nil && user.LoggedOut() {
auth.CloseSession(sess.ID)
}
return
}
}
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(404)
w.Write([]byte("Not Found: " + req.URL.Path))
}
func (router *Router) Resource(mount string, list, create ResourceFunc, get, update, delete ResourceIDFunc) {
router.Route(mount, NewResource(list, create, get, update, delete))
}
func (router *Router) Static(mount string, filePath string) {
router.Route(mount, NewStatic(filePath))
}
func (router *Router) Function(mount string, function FunctionHandlerFunc) {
router.Route(mount, &functionHandler{function})
}
func (router *Router) Listen(host string, port int) (*http.Server, error) {
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", host, port),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: router,
}
return srv, srv.ListenAndServe()
}