golang-exercises/query-cpu/cmd/client.go

64 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-03-26 18:55:52 +01:00
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"bufio"
2024-03-26 18:55:52 +01:00
"fmt"
"net"
"os"
2024-03-26 18:55:52 +01:00
//"net"
"github.com/spf13/cobra"
)
// clientCmd represents the client command
var clientCmd = &cobra.Command{
Use: "client",
Short: "Connect to a query-cpu server",
Long: `Send a message to a server using net.Dial()`,
2024-03-26 18:55:52 +01:00
Run: func(cmd *cobra.Command, args []string) {
if len(os.Args) != 2 {
}
client(cmd)
2024-03-26 18:55:52 +01:00
},
}
func init() {
rootCmd.AddCommand(clientCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
clientCmd.PersistentFlags().String("ip", "", "Server IP")
clientCmd.PersistentFlags().String("port", "", "Server port")
clientCmd.PersistentFlags().String("message", "", "Message we're gonna send to the server")
2024-03-26 18:55:52 +01:00
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// clientCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func client(cmd *cobra.Command) {
ip, _ := cmd.Flags().GetString("ip")
port, _ := cmd.Flags().GetString("port")
message, _ := cmd.Flags().GetString("message")
if ip == "" || port == "" || message == "" {
fmt.Println("Not enough arguments, run \"-h\" parameter to see all the parameters!")
os.Exit(1)
}
socket := ip + ":" + port
conn, err := net.Dial("tcp", socket)
cobra.CheckErr(err)
formattedMessage := fmt.Sprintf("%v\r\n", message)
fmt.Fprintf(conn, formattedMessage)
status, err := bufio.NewReader(conn).ReadString('\n')
fmt.Print(status)
2024-03-26 18:55:52 +01:00
}