From 1c7937dd222f789c92f280f681387af439efe78d Mon Sep 17 00:00:00 2001 From: ChronosX88 Date: Mon, 29 Jul 2019 18:08:13 +0400 Subject: [PATCH] feat: Add ability to change listening port --- cmd/main.go | 11 +++++++++-- internal/server.go | 15 ++++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index abb3929..978b5b2 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,22 +2,29 @@ package main import ( "log" + "strconv" "github.com/nxshock/signaller/internal" "github.com/nxshock/signaller/internal/backends/memory" ) var ( - server *internal.Server + server *internal.Server + defaultPortNumber = 8008 ) func init() { - server = internal.New() + var err error + server, err = internal.NewServer(defaultPortNumber) + if err != nil { + panic(err) + } server.Address = "localhost" server.Backend = memory.NewBackend(server.Address) server.Backend.Register("andrew", "1", "") } func main() { + log.Println("Server started on port " + strconv.Itoa(defaultPortNumber)) log.Println(server.Run()) } diff --git a/internal/server.go b/internal/server.go index 1a9551d..4439a88 100644 --- a/internal/server.go +++ b/internal/server.go @@ -5,6 +5,10 @@ import ( "github.com/gorilla/mux" + "errors" + + "strconv" + "github.com/nxshock/signaller/internal/models/capabilities" ) @@ -20,7 +24,8 @@ type Server struct { Backend Backend } -func New() *Server { +func NewServer(port int) (*Server, error) { + router := mux.NewRouter() router.HandleFunc("/_matrix/client/versions", VersionHandler) router.HandleFunc("/_matrix/client/r0/login", LoginHandler) @@ -34,8 +39,12 @@ func New() *Server { router.HandleFunc("/_matrix/client/r0/capabilities", CapabilitiesHandler) router.HandleFunc("/", RootHandler) + if port <= 0 || port > 65535 { + return nil, errors.New("invalid port number") + } + httpServer := new(http.Server) - httpServer.Addr = ":8008" + httpServer.Addr = ":" + strconv.Itoa(port) httpServer.Handler = router server := &Server{ @@ -43,7 +52,7 @@ func New() *Server { router: router} currServer = server - return server + return server, nil } func (server *Server) Run() error {