250 lines
5.3 KiB
Go
Raw Normal View History

2024-03-22 14:08:24 +00:00
package web
2023-07-18 16:02:57 +00:00
import (
2024-03-26 21:46:16 +00:00
"bufio"
2024-03-28 14:04:39 +00:00
"bytes"
2024-03-26 21:46:16 +00:00
"fmt"
"io"
2023-07-21 21:23:49 +00:00
"log"
2024-03-12 21:31:45 +00:00
"net"
"os"
"os/signal"
2024-03-28 14:04:39 +00:00
"strconv"
2024-03-26 21:46:16 +00:00
"strings"
2024-03-14 11:52:03 +00:00
"sync"
2024-03-12 21:31:45 +00:00
"syscall"
2023-07-18 16:02:57 +00:00
"git.akyoto.dev/go/router"
)
2024-03-14 11:52:03 +00:00
// Server is the interface for an HTTP server.
type Server interface {
Get(path string, handler Handler)
2024-03-28 11:22:45 +00:00
Request(method string, path string, headers []Header, body io.Reader) Response
2024-03-14 11:52:03 +00:00
Router() *router.Router[Handler]
Run(address string) error
Use(handlers ...Handler)
2023-07-18 16:02:57 +00:00
}
2024-03-14 11:52:03 +00:00
// server is an HTTP server.
type server struct {
handlers []Handler
2024-03-27 23:30:49 +00:00
contextPool sync.Pool
2024-03-26 21:46:16 +00:00
router *router.Router[Handler]
2024-03-14 11:52:03 +00:00
errorHandler func(Context, error)
}
2024-03-22 14:08:24 +00:00
// NewServer creates a new HTTP server.
func NewServer() Server {
2024-03-26 21:46:16 +00:00
r := &router.Router[Handler]{}
2024-03-14 11:52:03 +00:00
s := &server{
2024-03-26 21:46:16 +00:00
router: r,
2024-03-13 19:18:01 +00:00
handlers: []Handler{
func(c Context) error {
2024-03-26 21:46:16 +00:00
ctx := c.(*context)
handler := r.LookupNoAlloc(ctx.request.method, ctx.request.path, ctx.request.addParameter)
2024-03-13 19:18:01 +00:00
if handler == nil {
2024-03-26 21:46:16 +00:00
ctx.SetStatus(404)
return nil
2024-03-13 19:18:01 +00:00
}
return handler(c)
},
},
2024-03-14 11:52:03 +00:00
errorHandler: func(ctx Context, err error) {
2024-03-16 14:22:47 +00:00
log.Println(ctx.Request().Path(), err)
2024-03-14 11:52:03 +00:00
},
}
2024-03-27 23:30:49 +00:00
s.contextPool.New = func() any { return s.newContext() }
2024-03-14 11:52:03 +00:00
return s
2023-07-18 16:02:57 +00:00
}
// Get registers your function to be called when the given GET path has been requested.
2024-03-14 11:52:03 +00:00
func (s *server) Get(path string, handler Handler) {
2024-03-26 21:46:16 +00:00
s.Router().Add("GET", path, handler)
2023-07-22 09:36:28 +00:00
}
2024-03-27 10:36:12 +00:00
// Request performs a synthetic request and returns the response.
// This function keeps the response in memory so it's slightly slower than a real request.
// However it is very useful inside tests where you don't want to spin up a real web server.
2024-03-28 11:22:45 +00:00
func (s *server) Request(method string, url string, headers []Header, body io.Reader) Response {
2024-03-27 10:36:12 +00:00
ctx := s.newContext()
2024-03-28 11:22:45 +00:00
ctx.request.headers = headers
2024-03-27 13:06:13 +00:00
s.handleRequest(ctx, method, url, io.Discard)
2024-03-27 10:36:12 +00:00
return ctx.Response()
}
2024-03-12 21:31:45 +00:00
// Run starts the server on the given address.
2024-03-26 21:46:16 +00:00
func (s *server) Run(address string) error {
2024-03-12 21:31:45 +00:00
listener, err := net.Listen("tcp", address)
if err != nil {
2024-03-13 15:57:36 +00:00
return err
2024-03-12 21:31:45 +00:00
}
2024-03-26 21:46:16 +00:00
defer listener.Close()
go func() {
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go s.handleConnection(conn)
}
}()
2024-03-12 21:31:45 +00:00
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
2024-03-26 21:46:16 +00:00
return nil
2024-03-12 21:31:45 +00:00
}
2024-03-13 19:18:01 +00:00
2024-03-14 11:52:03 +00:00
// Router returns the router used by the server.
func (s *server) Router() *router.Router[Handler] {
2024-03-26 21:46:16 +00:00
return s.router
2024-03-14 11:52:03 +00:00
}
2024-03-13 19:18:01 +00:00
// Use adds handlers to your handlers chain.
2024-03-14 11:52:03 +00:00
func (s *server) Use(handlers ...Handler) {
last := s.handlers[len(s.handlers)-1]
s.handlers = append(s.handlers[:len(s.handlers)-1], handlers...)
s.handlers = append(s.handlers, last)
2024-03-13 19:18:01 +00:00
}
2024-03-26 21:46:16 +00:00
// handleConnection handles an accepted connection.
func (s *server) handleConnection(conn net.Conn) {
2024-03-27 21:12:16 +00:00
var (
2024-03-27 23:30:49 +00:00
ctx = s.contextPool.Get().(*context)
2024-03-27 21:12:16 +00:00
method string
url string
)
2024-03-27 23:30:49 +00:00
ctx.reader.Reset(conn)
defer conn.Close()
defer s.contextPool.Put(ctx)
2024-03-26 21:46:16 +00:00
for {
2024-03-28 13:27:40 +00:00
// Read the HTTP request line
message, err := ctx.reader.ReadString('\n')
2024-03-26 21:46:16 +00:00
2024-03-28 13:27:40 +00:00
if err != nil {
return
}
2024-03-26 21:46:16 +00:00
2024-03-28 13:27:40 +00:00
space := strings.IndexByte(message, ' ')
2024-03-26 21:46:16 +00:00
2024-03-28 13:27:40 +00:00
if space <= 0 {
fmt.Fprint(conn, "HTTP/1.1 400 Bad Request\r\n\r\n")
return
}
2024-03-26 21:46:16 +00:00
2024-03-28 13:27:40 +00:00
method = message[:space]
2024-03-27 21:12:16 +00:00
2024-03-28 13:27:40 +00:00
if !isRequestMethod(method) {
fmt.Fprint(conn, "HTTP/1.1 400 Bad Request\r\n\r\n")
return
}
2024-03-26 21:46:16 +00:00
2024-03-28 13:27:40 +00:00
lastSpace := strings.LastIndexByte(message, ' ')
2024-03-26 21:46:16 +00:00
2024-03-28 13:27:40 +00:00
if lastSpace == space {
lastSpace = len(message) - len("\r\n")
2024-03-26 21:46:16 +00:00
}
2024-03-28 13:27:40 +00:00
url = message[space+1 : lastSpace]
2024-03-27 21:12:16 +00:00
// Add headers until we meet an empty line
for {
2024-03-28 13:27:40 +00:00
message, err = ctx.reader.ReadString('\n')
2024-03-27 21:12:16 +00:00
if err != nil {
return
}
if message == "\r\n" {
break
}
2024-03-26 21:46:16 +00:00
2024-03-27 21:12:16 +00:00
colon := strings.IndexByte(message, ':')
if colon <= 0 {
continue
}
key := message[:colon]
value := message[colon+2 : len(message)-2]
2024-03-28 11:22:45 +00:00
ctx.request.headers = append(ctx.request.headers, Header{
2024-03-27 21:12:16 +00:00
Key: key,
Value: value,
})
}
// Handle the request
2024-03-27 13:06:13 +00:00
s.handleRequest(ctx, method, url, conn)
2024-03-27 23:30:49 +00:00
// Clean up the context
2024-03-27 21:12:16 +00:00
ctx.request.headers = ctx.request.headers[:0]
ctx.request.body = ctx.request.body[:0]
ctx.response.headers = ctx.response.headers[:0]
ctx.response.body = ctx.response.body[:0]
2024-03-26 21:46:16 +00:00
ctx.params = ctx.params[:0]
ctx.handlerCount = 0
ctx.status = 200
}
}
// handleRequest handles the given request.
2024-03-27 13:06:13 +00:00
func (s *server) handleRequest(ctx *context, method string, url string, writer io.Writer) {
2024-03-26 21:46:16 +00:00
ctx.method = method
2024-03-27 19:41:27 +00:00
ctx.scheme, ctx.host, ctx.path, ctx.query = parseURL(url)
2024-03-26 21:46:16 +00:00
err := s.handlers[0](ctx)
if err != nil {
s.errorHandler(ctx, err)
}
2024-03-28 14:04:39 +00:00
tmp := bytes.Buffer{}
tmp.WriteString("HTTP/1.1 ")
tmp.WriteString(strconv.Itoa(int(ctx.status)))
tmp.WriteString("\r\nContent-Length: ")
tmp.WriteString(strconv.Itoa(len(ctx.response.body)))
2024-03-28 14:19:46 +00:00
tmp.WriteString("\r\n")
for _, header := range ctx.response.headers {
tmp.WriteString(header.Key)
tmp.WriteString(": ")
tmp.WriteString(header.Value)
tmp.WriteString("\r\n")
}
tmp.WriteString("\r\n")
2024-03-28 14:04:39 +00:00
tmp.Write(ctx.response.body)
writer.Write(tmp.Bytes())
2024-03-26 21:46:16 +00:00
}
2024-03-27 10:36:12 +00:00
// newContext allocates a new context with the default state.
2024-03-26 21:46:16 +00:00
func (s *server) newContext() *context {
return &context{
server: s,
request: request{
2024-03-27 23:30:49 +00:00
reader: bufio.NewReader(nil),
2024-03-27 21:12:16 +00:00
body: make([]byte, 0),
2024-03-28 11:22:45 +00:00
headers: make([]Header, 0, 8),
2024-03-27 21:12:16 +00:00
params: make([]router.Parameter, 0, 8),
2024-03-26 21:46:16 +00:00
},
response: response{
2024-03-27 21:12:16 +00:00
body: make([]byte, 0, 1024),
2024-03-28 11:22:45 +00:00
headers: make([]Header, 0, 8),
2024-03-27 21:12:16 +00:00
status: 200,
2024-03-26 21:46:16 +00:00
},
}
}