From 9c39b1c462c66cea6fc564e2ab99ddc849b5db27 Mon Sep 17 00:00:00 2001 From: raul Date: Thu, 28 Mar 2024 15:03:58 +0100 Subject: [PATCH] Added custom port flag to server command --- query-cpu/cmd/server.go | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/query-cpu/cmd/server.go b/query-cpu/cmd/server.go index 369aae1..4a25abe 100644 --- a/query-cpu/cmd/server.go +++ b/query-cpu/cmd/server.go @@ -26,7 +26,7 @@ Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { - server() + server(cmd) }, } @@ -37,17 +37,26 @@ func init() { // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: - // serverCmd.PersistentFlags().String("foo", "", "A help for foo") + //serverCmd.PersistentFlags().String("", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") + serverCmd.Flags().String("port", "1302", "Port to listen on") } -func server() { - ln, err := net.Listen("tcp", ":8080") - catchErr(err) - fmt.Println("Listening on port 8080...") +func server(cmd *cobra.Command) { + var lport string + port, _ := cmd.Flags().GetString("port") + if port != "" { + lport = port + } else { + lport = "1302" + } + + ln, err := net.Listen("tcp", ":"+lport) + cobra.CheckErr(err) + fmt.Printf("Listening on port %v...\n", lport) for { conn, err := ln.Accept() catchErr(err)