72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"net/http"
|
|
|
|
"git.nwaifu.su/sergey/MyGoServer/cmd/apiserver/config"
|
|
"git.nwaifu.su/sergey/MyGoServer/internal/apiserver/logger"
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
type contextKey struct {
|
|
key string
|
|
}
|
|
|
|
var connContextKey = &contextKey{"http-conn"}
|
|
|
|
func saveConnInContext(ctx context.Context, c net.Conn) context.Context {
|
|
return context.WithValue(ctx, connContextKey, c)
|
|
}
|
|
|
|
// Server represents the HTTP server
|
|
type Server struct {
|
|
config *config.Config
|
|
router *mux.Router
|
|
server *http.Server
|
|
}
|
|
|
|
// NewServer creates a new server instance
|
|
func NewServer(cfg *config.Config) *Server {
|
|
s := &Server{
|
|
config: cfg,
|
|
}
|
|
|
|
// Initialize logger
|
|
logger.Initialize(cfg.Logging.Level, cfg.Logging.Format, cfg.Logging.Output)
|
|
|
|
// Create router
|
|
s.router = mux.NewRouter()
|
|
s.setupRoutes()
|
|
|
|
// Create HTTP server
|
|
s.server = &http.Server{
|
|
Addr: cfg.Server.Address,
|
|
Handler: s.router,
|
|
ConnContext: saveConnInContext,
|
|
}
|
|
|
|
return s
|
|
}
|
|
|
|
// Start starts the server
|
|
func (s *Server) Start() error {
|
|
return s.server.ListenAndServe()
|
|
}
|
|
|
|
// GetRouter returns the HTTP router
|
|
func (s *Server) GetRouter() *mux.Router {
|
|
return s.router
|
|
}
|
|
|
|
// GetServer returns the HTTP server instance
|
|
func (s *Server) GetServer() *http.Server {
|
|
return s.server
|
|
}
|
|
|
|
// GetConfig returns the server configuration
|
|
func (s *Server) GetConfig() *config.Config {
|
|
return s.config
|
|
}
|