56 lines
916 B
Go
56 lines
916 B
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type Server struct {
|
|
srv *http.Server
|
|
}
|
|
|
|
func NewServer(addr string) *Server {
|
|
srv := http.Server{
|
|
ReadTimeout: time.Second * 3,
|
|
WriteTimeout: time.Second * 3,
|
|
IdleTimeout: time.Second * 2,
|
|
ReadHeaderTimeout: time.Second * 3,
|
|
Addr: addr,
|
|
}
|
|
|
|
return &Server{
|
|
srv: &srv,
|
|
}
|
|
}
|
|
|
|
func (s *Server) RegisterHandler(h http.Handler) {
|
|
s.srv.Handler = h
|
|
}
|
|
|
|
func (s *Server) Run() error {
|
|
err := s.srv.ListenAndServe()
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
return nil
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func (s *Server) Close() error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
|
defer cancel()
|
|
|
|
return s.srv.Shutdown(ctx)
|
|
}
|
|
|
|
func randomID() string {
|
|
var randombuffer [4]byte
|
|
_, _ = rand.Read(randombuffer[:])
|
|
|
|
return hex.EncodeToString(randombuffer[:])
|
|
}
|