This repository has been archived on 2022-11-30. You can view files and clone it, but cannot push or open issues or pull requests.
tacitus/http/server.go

54 lines
824 B
Go
Raw Normal View History

2017-09-08 10:57:39 -07:00
package http
import (
"net"
"net/http"
2017-09-17 18:50:57 -07:00
"github.com/kcotugno/tacitus"
2017-09-08 10:57:39 -07:00
)
const DefaultAddr = ":8080"
type Server struct {
Addr string
2017-09-09 10:14:50 -07:00
Handler *Mux
2017-09-08 10:57:39 -07:00
Err chan error
listener net.Listener
2017-09-17 18:50:57 -07:00
logger tacitus.Logger
2017-09-08 10:57:39 -07:00
}
func NewServer() *Server {
2017-09-09 10:14:50 -07:00
return &Server{Addr: DefaultAddr,
Handler: NewMux()}
2017-09-08 10:57:39 -07:00
}
func (s *Server) Open() error {
ln, err := net.Listen("tcp", s.Addr)
if err != nil {
2017-09-17 18:50:57 -07:00
s.logger.Info(`Error opening socket on %v. error="%v"`, s.Addr, err)
2017-09-08 10:57:39 -07:00
return err
}
2017-09-17 18:50:57 -07:00
s.logger.Info("Listening on %v", s.Addr)
2017-09-08 10:57:39 -07:00
s.listener = ln
go func() { http.Serve(s.listener, s.Handler) }()
return nil
}
2017-09-17 18:50:57 -07:00
func (s *Server) Close() {
2017-09-08 10:57:39 -07:00
if s.listener != nil {
s.listener.Close()
2017-09-17 18:50:57 -07:00
s.logger.Info("Socket closed")
2017-09-08 10:57:39 -07:00
}
2017-09-17 18:50:57 -07:00
}
2017-09-08 10:57:39 -07:00
2017-09-17 18:50:57 -07:00
func (s *Server) SetLogger(logger tacitus.Logger) {
s.logger = logger
s.Handler.Logger = logger
2017-09-08 10:57:39 -07:00
}