And the other connects to a UDP socket and sends data over it:
func socketConnection() {
hostName := "localhost"
portNum := "6000"
service := hostName + ":" + portNum
RemoteAddr, err := net.ResolveUDPAddr("udp", service)
conn, err := net.DialUDP("udp", nil, RemoteAddr)
if err != nil {
log.Fatal(err)
}
log.Printf("Established connection to %s \n", service)
log.Printf("Remote UDP address : %s \n", conn.RemoteAddr().String())
defer conn.Close()
message := []byte(**HERE IS WHERE I WANT TO PUT pepperText**)
conn.Write(message)
}
I want to be able to access the variable âpepperTxtâ in the socketConnection function. How do I do this, Iâve tried making the variable global but still no luck. Many, many thanks for any help.
Ideally you would pass it as a parameter to the socketConnection() function. However, socketConnection isnât called from formHandler, so how does it get called? How do you ensure that itâs called afterformHandler (or the variable would be unset)? You can make the variable package scoped (âglobalâ, for Go purposes), but there are things to consider like what would happen if socketConnection() is called at the same time as formHandler changes the value (this is a data race).
pepperTxt never will be available in socketConnection() as you are defining it in the formHandler function so it is not visible outside of the formHandler function
Also keep in mind that := is the shorthand notation for var something =. Both act in the same way, except := is only valid within a function or method, while the var syntax is valid everywhere.
Thank you, this worked! I passed it as a variable and and called âgo socketConnection(pepperTxt)â at the end of the formHandler and received it on the other end. Many thanks everyone!
Iâd suggest, and this is assuming that you are going to call your socketConnection() function from within your handler to write your pepperText as a message to the connection, that you pass your pepperText variable into your socketConnection function, and use it that way.
Youâll have to update your socketConnection function, which might warrant a name change to something like socketConnectionMessage, but code wise youâd need to do this: