78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
package server
|
|
|
|
import (
|
|
"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)
|
|
log.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 {
|
|
return s.Server.ListenAndServe()
|
|
}
|
|
func (s *Server) Router(router http.Handler) *Server {
|
|
s.Handler = router
|
|
return s
|
|
}
|