Writing a CLI application in GoLang and want to use URL across different sessions/commands. Implementing CLI through Cobra where I want to configure URL at the beginning and then keep using it across other commands.
Tried to use below approach -
os.Setenv("URL", URL) os.Getenv("URL")
Above approach works only inside the same process (doesn't work if set and get processes are different).
Any idea how can we do it ?
Update: I wanted to know if it's possible to be done inside Go? I know it can be easily done by storing it in file/db or even setting up in environment variable but exploring ways to do it in Go.
You could establish a simple listener, serving requests to other processes. It could receive and provide any kind of content.
It's quite easy to set up an listening daemon with go, using net.Listen("tcp",":8080"). Perhaps you could take this snippets as boilerplate:
package main
import (
"fmt"
"io"
"log"
"net"
"strings"
)
type textProcessor struct {
input *string
}
func (this textProcessor) Write(b []byte) (int, error) {
*this.input = string(b)
return len(strings.TrimSpace(string(b))), nil
}
func main() {
t := textProcessor{new(string)}
l, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// Wait for connection
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
io.Copy(t, conn)
fmt.Print("Echo: ", *t.input)
conn.Close()
}
}
Check it out with telnet localhost 8080 and enter some rubbish afterwards.