package server import ( "context" "io" "log" "net" "net/http" "os" "os/signal" "syscall" "git.akyoto.dev/go/router" ) // Server represents a single web service. type Server struct { Router *router.Router[Handler] Config Configuration handlers []Handler } // New creates a new server. func New() *Server { return &Server{ Router: router.New[Handler](), Config: defaultConfig(), handlers: []Handler{ func(c Context) error { handler := c.(*ctx).server.Router.LookupNoAlloc(c.Method(), c.Path(), c.(*ctx).addParameter) if handler == nil { return c.Status(http.StatusNotFound).String(http.StatusText(http.StatusNotFound)) } return handler(c) }, }, } } // 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(http.MethodGet, path, handler) } // Post registers your function to be called when the given POST path has been requested. func (server *Server) Post(path string, handler Handler) { server.Router.Add(http.MethodPost, path, handler) } // Delete registers your function to be called when the given DELETE path has been requested. func (server *Server) Delete(path string, handler Handler) { server.Router.Add(http.MethodDelete, path, handler) } // Put registers your function to be called when the given PUT path has been requested. func (server *Server) Put(path string, handler Handler) { server.Router.Add(http.MethodPut, path, handler) } // ServeHTTP responds to the given request. func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) { ctx := contextPool.Get().(*ctx) ctx.request = request ctx.response = response ctx.server = server err := server.handlers[0](ctx) if err != nil { response.(io.StringWriter).WriteString(err.Error()) log.Println(request.URL, err) } ctx.paramCount = 0 ctx.handlerCount = 0 contextPool.Put(ctx) } // 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, } listener, err := net.Listen("tcp", address) if err != nil { return err } go srv.Serve(listener) 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) } // Use adds handlers to your handlers chain. func (server *Server) Use(handlers ...Handler) { last := server.handlers[len(server.handlers)-1] server.handlers = append(server.handlers[:len(server.handlers)-1], handlers...) server.handlers = append(server.handlers, last) }