2024-01-10 20:26:19 +08:00
|
|
|
package nf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2024-01-11 22:29:30 +08:00
|
|
|
"strings"
|
2024-01-10 20:26:19 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type App struct {
|
2024-01-11 18:16:41 +08:00
|
|
|
*RouterGroup
|
2024-01-10 20:26:19 +08:00
|
|
|
router *router
|
2024-01-11 18:16:41 +08:00
|
|
|
groups []*RouterGroup
|
2024-01-10 20:26:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (a *App) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
2024-01-11 18:16:41 +08:00
|
|
|
c := newContext(writer, request)
|
2024-01-11 22:29:30 +08:00
|
|
|
for _, group := range a.groups {
|
|
|
|
if strings.HasPrefix(request.URL.Path, group.prefix) {
|
|
|
|
c.handlers = append(c.handlers, group.middlewares...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-10 20:26:19 +08:00
|
|
|
if err := a.router.handle(c); err != nil {
|
|
|
|
writer.WriteHeader(500)
|
|
|
|
_, _ = writer.Write([]byte(err.Error()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-11 18:16:41 +08:00
|
|
|
func (a *App) Get(path string, handlers ...HandlerFunc) {
|
2024-01-11 22:29:30 +08:00
|
|
|
verifyHandlers(path, handlers...)
|
|
|
|
a.router.addRoute(http.MethodGet, path, handlers...)
|
|
|
|
}
|
2024-01-11 18:16:41 +08:00
|
|
|
|
2024-01-11 22:29:30 +08:00
|
|
|
func (a *App) Post(path string, handlers ...HandlerFunc) {
|
|
|
|
verifyHandlers(path, handlers...)
|
|
|
|
a.router.addRoute(http.MethodPost, path, handlers...)
|
|
|
|
}
|
2024-01-11 18:16:41 +08:00
|
|
|
|
2024-01-11 22:29:30 +08:00
|
|
|
func (a *App) Delete(path string, handlers ...HandlerFunc) {
|
|
|
|
verifyHandlers(path, handlers...)
|
|
|
|
a.router.addRoute(http.MethodDelete, path, handlers...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *App) Put(path string, handlers ...HandlerFunc) {
|
|
|
|
verifyHandlers(path, handlers...)
|
|
|
|
a.router.addRoute(http.MethodPut, path, handlers...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *App) Patch(path string, handlers ...HandlerFunc) {
|
|
|
|
verifyHandlers(path, handlers...)
|
|
|
|
a.router.addRoute(http.MethodPatch, path, handlers...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *App) Head(path string, handlers ...HandlerFunc) {
|
|
|
|
verifyHandlers(path, handlers...)
|
|
|
|
a.router.addRoute(http.MethodHead, path, handlers...)
|
2024-01-10 20:26:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (a *App) Run(address string) error {
|
|
|
|
fmt.Println(banner + "nf serve at: " + address + "\n")
|
|
|
|
return http.ListenAndServe(address, a)
|
|
|
|
}
|