nf/app.go

40 lines
818 B
Go
Raw Normal View History

2024-01-10 20:26:19 +08:00
package nf
import (
"fmt"
"net/http"
)
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-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) {
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...)
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)
}