2023-04-24 00:49:53 +04:00
|
|
|
package http
|
2022-02-06 02:22:23 +04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
2022-03-07 23:55:00 +04:00
|
|
|
"os"
|
2022-02-06 02:22:23 +04:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/julienschmidt/httprouter"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HttpServer struct {
|
|
|
|
server *http.Server
|
|
|
|
router *httprouter.Router
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewHttpServer() *HttpServer {
|
|
|
|
r := httprouter.New()
|
|
|
|
return &HttpServer{
|
|
|
|
server: &http.Server{
|
|
|
|
ReadTimeout: 3 * time.Second,
|
|
|
|
WriteTimeout: 3 * time.Second,
|
|
|
|
Handler: r,
|
|
|
|
},
|
|
|
|
router: r,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *HttpServer) GET(path string, handler http.HandlerFunc) {
|
|
|
|
s.router.Handler(http.MethodGet, path, handler)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *HttpServer) POST(path string, handler http.HandlerFunc) {
|
|
|
|
s.router.Handler(http.MethodPost, path, handler)
|
|
|
|
}
|
|
|
|
|
2022-07-01 03:26:15 +04:00
|
|
|
func (s *HttpServer) DELETE(path string, handler http.HandlerFunc) {
|
|
|
|
s.router.Handler(http.MethodDelete, path, handler)
|
|
|
|
}
|
|
|
|
|
2022-02-06 15:24:37 +04:00
|
|
|
func (s *HttpServer) ServeStatic(path string, fsys http.FileSystem) {
|
|
|
|
s.router.ServeFiles(path, fsys)
|
|
|
|
}
|
|
|
|
|
2022-02-07 22:50:46 +04:00
|
|
|
func (s *HttpServer) SetNotFoundHandler(handler http.HandlerFunc) {
|
|
|
|
s.router.NotFound = handler
|
|
|
|
}
|
|
|
|
|
2022-02-06 15:24:37 +04:00
|
|
|
// GetURLParam wrapper around underlying router for getting URL parameters.
|
|
|
|
func GetURLParam(r *http.Request, param string) string {
|
|
|
|
return httprouter.ParamsFromContext(r.Context()).ByName(param)
|
2022-02-06 02:22:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *HttpServer) Start(network, address string) error {
|
|
|
|
listener, err := net.Listen(network, address)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-03-07 23:55:00 +04:00
|
|
|
if listener.Addr().Network() == "unix" {
|
|
|
|
os.Chmod(address, 0777)
|
|
|
|
}
|
|
|
|
|
2022-02-06 02:22:23 +04:00
|
|
|
go func() {
|
|
|
|
if err = s.server.Serve(listener); err != nil && err != http.ErrServerClosed {
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *HttpServer) Stop() error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
if err := s.server.Shutdown(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|