Removed net/http

This commit is contained in:
2024-03-26 22:46:16 +01:00
parent f4617248d8
commit 271e1cd5bd
11 changed files with 230 additions and 629 deletions

168
Server.go
View File

@ -1,12 +1,14 @@
package web
import (
"context"
"bufio"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
@ -15,13 +17,13 @@ import (
// Server is the interface for an HTTP server.
type Server interface {
http.Handler
Delete(path string, handler Handler)
Get(path string, handler Handler)
Post(path string, handler Handler)
Put(path string, handler Handler)
Router() *router.Router[Handler]
Run(address string) error
Test(method string, path string, body io.Reader) Response
Use(handlers ...Handler)
}
@ -29,41 +31,35 @@ type Server interface {
type server struct {
pool sync.Pool
handlers []Handler
router router.Router[Handler]
router *router.Router[Handler]
errorHandler func(Context, error)
config config
}
// NewServer creates a new HTTP server.
func NewServer() Server {
r := &router.Router[Handler]{}
s := &server{
router: router.Router[Handler]{},
config: defaultConfig(),
router: r,
handlers: []Handler{
func(c Context) error {
ctx := c.(*ctx)
method := ctx.request.Method()
path := ctx.request.Path()
handler := ctx.server.router.LookupNoAlloc(method, path, ctx.addParameter)
ctx := c.(*context)
handler := r.LookupNoAlloc(ctx.request.method, ctx.request.path, ctx.request.addParameter)
if handler == nil {
return ctx.Status(http.StatusNotFound).String(http.StatusText(http.StatusNotFound))
ctx.SetStatus(404)
return nil
}
return handler(c)
},
},
errorHandler: func(ctx Context, err error) {
ctx.Response().WriteString(err.Error())
log.Println(ctx.Request().Path(), err)
},
}
s.pool.New = func() any {
return &ctx{
server: s,
params: make([]router.Parameter, 0, 8),
}
return s.newContext()
}
return s
@ -71,72 +67,55 @@ func NewServer() Server {
// Get registers your function to be called when the given GET path has been requested.
func (s *server) Get(path string, handler Handler) {
s.Router().Add(http.MethodGet, path, handler)
s.Router().Add("GET", path, handler)
}
// Post registers your function to be called when the given POST path has been requested.
func (s *server) Post(path string, handler Handler) {
s.Router().Add(http.MethodPost, path, handler)
s.Router().Add("POST", path, handler)
}
// Delete registers your function to be called when the given DELETE path has been requested.
func (s *server) Delete(path string, handler Handler) {
s.Router().Add(http.MethodDelete, path, handler)
s.Router().Add("DELETE", path, handler)
}
// Put registers your function to be called when the given PUT path has been requested.
func (s *server) Put(path string, handler Handler) {
s.Router().Add(http.MethodPut, path, handler)
}
// ServeHTTP responds to the given request.
func (s *server) ServeHTTP(res http.ResponseWriter, req *http.Request) {
ctx := s.pool.Get().(*ctx)
ctx.request = request{req}
ctx.response = response{res}
err := s.handlers[0](ctx)
if err != nil {
s.errorHandler(ctx, err)
}
ctx.params = ctx.params[:0]
ctx.handlerCount = 0
s.pool.Put(ctx)
s.Router().Add("PUT", path, handler)
}
// Run starts the server on the given address.
func (server *server) Run(address string) error {
srv := &http.Server{
Addr: address,
Handler: server,
ReadTimeout: server.config.Timeout.Read,
WriteTimeout: server.config.Timeout.Write,
IdleTimeout: server.config.Timeout.Idle,
ReadHeaderTimeout: server.config.Timeout.ReadHeader,
}
func (s *server) Run(address string) error {
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
go srv.Serve(listener)
defer listener.Close()
go func() {
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go s.handleConnection(conn)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), server.config.Timeout.Shutdown)
defer cancel()
return srv.Shutdown(ctx)
return nil
}
// Router returns the router used by the server.
func (s *server) Router() *router.Router[Handler] {
return &s.router
return s.router
}
// Use adds handlers to your handlers chain.
@ -145,3 +124,84 @@ func (s *server) Use(handlers ...Handler) {
s.handlers = append(s.handlers[:len(s.handlers)-1], handlers...)
s.handlers = append(s.handlers, last)
}
// handleConnection handles an accepted connection.
func (s *server) handleConnection(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return
}
space := strings.IndexByte(message, ' ')
if space <= 0 {
continue
}
method := message[:space]
if method != "GET" {
continue
}
lastSpace := strings.LastIndexByte(message, ' ')
if lastSpace == -1 {
lastSpace = len(message)
}
path := message[space+1 : lastSpace]
ctx := s.pool.Get().(*context)
s.handleRequest(ctx, method, path, conn)
ctx.body = ctx.body[:0]
ctx.params = ctx.params[:0]
ctx.handlerCount = 0
ctx.status = 200
s.pool.Put(ctx)
}
}
// handleRequest handles the given request.
func (s *server) handleRequest(ctx *context, method string, path string, writer io.Writer) {
ctx.method = method
ctx.path = path
err := s.handlers[0](ctx)
if err != nil {
s.errorHandler(ctx, err)
}
_, err = fmt.Fprintf(writer, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n%s\r\n%s", ctx.status, "OK", len(ctx.body), ctx.response.headerText(), ctx.body)
if err != nil {
s.errorHandler(ctx, err)
}
}
func (s *server) Test(method string, path string, body io.Reader) Response {
ctx := s.newContext()
ctx.method = method
ctx.path = path
s.handleRequest(ctx, method, path, io.Discard)
return ctx.Response()
}
func (s *server) newContext() *context {
return &context{
server: s,
request: request{
params: make([]router.Parameter, 0, 8),
},
response: response{
body: make([]byte, 0, 1024),
status: 200,
},
}
}