Added custom port flag to server command

This commit is contained in:
raul 2024-03-28 15:03:58 +01:00
parent 4e30581a5e
commit 9c39b1c462
1 changed files with 15 additions and 6 deletions

View File

@ -26,7 +26,7 @@ Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files This application is a tool to generate the needed files
to quickly create a Cobra application.`, to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) { 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 // Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.: // 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 // Cobra supports local flags which will only run when this command
// is called directly, e.g.: // is called directly, e.g.:
// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") // serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
serverCmd.Flags().String("port", "1302", "Port to listen on")
} }
func server() { func server(cmd *cobra.Command) {
ln, err := net.Listen("tcp", ":8080") var lport string
catchErr(err) port, _ := cmd.Flags().GetString("port")
fmt.Println("Listening on port 8080...") 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 { for {
conn, err := ln.Accept() conn, err := ln.Accept()
catchErr(err) catchErr(err)