nf/app.go
2024-01-11 18:16:41 +08:00

40 lines
818 B
Go

package nf
import (
"fmt"
"net/http"
)
type App struct {
*RouterGroup
router *router
groups []*RouterGroup
}
func (a *App) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
c := newContext(writer, request)
if err := a.router.handle(c); err != nil {
writer.WriteHeader(500)
_, _ = writer.Write([]byte(err.Error()))
}
}
func (a *App) Get(path string, handlers ...HandlerFunc) {
if len(handlers) == 0 {
panic(fmt.Sprintf("missing handler in route: %s", path))
}
for _, handler := range handlers {
if handler == nil {
panic(fmt.Sprintf("nil handler found in route: %s", path))
}
}
a.router.addRoute(http.MethodGet, path, handlers...)
}
func (a *App) Run(address string) error {
fmt.Println(banner + "nf serve at: " + address + "\n")
return http.ListenAndServe(address, a)
}