52 lines
1.2 KiB
Go
Raw Normal View History

2023-07-18 19:48:38 +00:00
package server
2023-07-18 16:02:57 +00:00
import (
2023-07-21 21:23:49 +00:00
"io"
"log"
2023-07-18 16:02:57 +00:00
"net/http"
"git.akyoto.dev/go/router"
)
// Handler is a function that deals with the given request/response context.
type Handler func(Context) error
// Server represents a single web service.
type Server struct {
router *router.Router[Handler]
}
// New creates a new server.
func New() *Server {
return &Server{
router: router.New[Handler](),
}
}
// Get registers your function to be called when the given GET path has been requested.
func (server *Server) Get(path string, handler Handler) {
server.router.Add("GET", path, handler)
}
// ServeHTTP responds to the given request.
func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
ctx := newContext(request, response)
handler := server.router.LookupNoAlloc(request.Method, request.URL.Path, ctx.addParameter)
if handler == nil {
response.WriteHeader(http.StatusNotFound)
2023-07-21 21:23:49 +00:00
response.(io.StringWriter).WriteString(http.StatusText(http.StatusNotFound))
2023-07-18 16:02:57 +00:00
contextPool.Put(ctx)
return
}
err := handler(ctx)
if err != nil {
2023-07-21 21:23:49 +00:00
response.(io.StringWriter).WriteString(err.Error())
log.Println(request.URL, err)
2023-07-18 16:02:57 +00:00
}
contextPool.Put(ctx)
}