go-server/server.go
Zeev Diukman 841c7b9e59 4
2025-03-08 17:51:24 +00:00

88 lines
1.9 KiB
Go

package server
import (
"fmt"
"log"
"net/http"
"strconv"
)
type Server struct {
_Name string
_Port int
_CertKey [2]string
*http.Server
}
// New creates a new Server instance.
// Returns:
// - *Server: a new server instance.
func New() *Server {
s := &Server{}
s.Server = &http.Server{}
return s
}
// Name sets the name of the server.
// Parameters:
// - name: the name to set for the server.
// Returns:
// - *Server: the server instance with the updated name.
func (s *Server) Name(name string) *Server {
s._Name = name
return s
}
// Port sets the port for the server.
// Parameters:
// - port: the port number to set for the server.
// Returns:
// - *Server: the server instance with the updated port.
func (s *Server) Port(port int) *Server {
s._Port = port
s.Addr = ":" + strconv.Itoa(port)
return s
}
func (s *Server) CertKey(path string, certFile string, keyFile string) *Server {
s._CertKey = [2]string{path + certFile, path + keyFile}
return s
}
// ListenAndServeTLS starts the server with TLS encryption.
// Parameters:
// - certFile: the path to the certificate file.
// - keyFile: the path to the key file.
// Returns:
// - error: an error if the server fails to start.
func (s *Server) ListenAndServeTLS() error {
name := s._Name
port := s._Port
p := strconv.Itoa(port)
fmt.Println("Starting TLS server (" + name + ") at " + p)
certFile := s._CertKey[0]
keyFile := s._CertKey[1]
err := s.Server.ListenAndServeTLS(certFile, keyFile)
if err != nil {
log.Fatalln(err.Error())
return err
}
return nil
}
func (s *Server) ListenAndServe() error {
name := s._Name
port := s._Port
p := strconv.Itoa(port)
fmt.Println("Starting server (" + name + ") at " + p)
err := s.Server.ListenAndServe()
if err != nil {
log.Fatalln(err.Error())
return err
}
return nil
}
func (s *Server) Router(router http.Handler) *Server {
s.Handler = router
return s
}