mirror of
https://github.com/nkanaev/yarr.git
synced 2025-12-15 08:37:21 +00:00
create feeds
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"regexp"
|
||||
"net/http"
|
||||
"github.com/nkanaev/yarr/storage"
|
||||
"log"
|
||||
)
|
||||
|
||||
@@ -15,6 +16,7 @@ type Route struct {
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
db *storage.Storage
|
||||
}
|
||||
|
||||
func p(path string, handler func(http.ResponseWriter, *http.Request)) Route {
|
||||
@@ -44,25 +46,37 @@ var routes []Route = []Route{
|
||||
}
|
||||
|
||||
func Vars(req *http.Request) map[string]string {
|
||||
if rv := req.Context().Value(0); rv != nil {
|
||||
if rv := req.Context().Value(ctxVars); rv != nil {
|
||||
return rv.(map[string]string)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func db(req *http.Request) *storage.Storage {
|
||||
if rv := req.Context().Value(ctxDB); rv != nil {
|
||||
return rv.(*storage.Storage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
ctxDB = 1
|
||||
ctxVars = 2
|
||||
)
|
||||
|
||||
func (h Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
for _, route := range routes {
|
||||
if route.urlRegex.MatchString(req.URL.Path) {
|
||||
ctx := context.WithValue(req.Context(), ctxDB, h.db)
|
||||
if route.urlRegex.NumSubexp() > 0 {
|
||||
vars := make(map[string]string)
|
||||
matches := route.urlRegex.FindStringSubmatchIndex(req.URL.Path)
|
||||
for i, key := range route.urlRegex.SubexpNames()[1:] {
|
||||
vars[key] = req.URL.Path[matches[i*2+2]:matches[i*2+3]]
|
||||
}
|
||||
ctx := context.WithValue(req.Context(), 0, vars)
|
||||
req = req.WithContext(ctx)
|
||||
ctx = context.WithValue(ctx, ctxVars, vars)
|
||||
}
|
||||
route.handler(rw, req)
|
||||
route.handler(rw, req.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -80,7 +94,8 @@ func writeJSON(rw http.ResponseWriter, data interface{}) {
|
||||
}
|
||||
|
||||
func New() *http.Server {
|
||||
h := Handler{}
|
||||
db, _ := storage.New()
|
||||
h := Handler{db: db}
|
||||
s := &http.Server{Addr: "127.0.0.1:8000", Handler: h}
|
||||
return s
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user