My problem is go run someprogram.go usecomand change_variable=value
is this possible and how I can make it?
import (
"github.com/spf13/cobra"
"fmt"
"math/rand"
"time"
"github.com/brocaar/lorawan"
MQTT "github.com/eclipse/paho.mqtt.golang"
lds "github.com/iegomez/loraserver-device-sim"
)
func mainCmd() *cobra.Command {
return &cobra.Command{
Use: "sensor", RunE: func(cmd *cobra.Command,args []string) error {
ip := "tcp://127.0.0.1:1883"
cmd.Println("O IP da gateway e o port são:",ip)
//Connect to the broker
opts :=MQTT.NewClientOptions() opts.AddBroker(ip)
See this is what my go file contains and I want in command line build the go file and execute and change the ip variable
If you want to change value of variable inside the code, you can use command line arguments. You can refer https://gobyexample.com/command-line-arguments
you can change the variables during build with go run -ldflags="-X..
. flags.
In this example, change the ip to become a variable at the start of your code.
var IP = "<default_ip>"
Then you can reference the variable in the rest of your code. Then run the code with
go run -ldflags="-X <package>.IP <new_ip_address>" program.go
So if your package is main
, and the program name is main.go
and the new IP is 0.0.0.0
you would run
go run -ldflags="-X main.IP 0.0.0.0" program.go
I used this however in my testing (with an =
sign, since it errored)
go run -ldflags="-X main.who=0.0.0.0" program.go
You can read this article here for more information