Issue
I’m new to Go – following problem: My program receives an http post request and now I want to forward data from it to an active TCP connection (the program runs a parallel TCP Server).
In main()
the handler is registered like this:
http.HandleFunc("/rcvtelegram", handleRestRequest)
and the http-handler function is therefore like this:
func handleRestRequest(w http.ResponseWriter, r *http.Request) {}
The TCP connection to the client is open with a net.Conn object which main()
knows. So ideally I would start a go routine with a TCP sender function that listens for an incoming string to send it through TCP. But how? With channels it seems I must pass all parameters but I don’t have the connection object in the http handler function. I also want to avoid making the tcp connection a global variable. I saw the Observer pattern but that scares me with its complexity as a newbie (and not sure if it solves my problem).
Thanks!
Solution
Use a struct type to hold the channel. Implement the http.Handler interface on the type:
type RestHandler struct {
ch chan string
}
func (h *RestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// insert body of the handleRestRequest here.
// Use h.ch <- someString to send string to connection
}
In your main function, create a channel for the TCP sender and start the sender in a goroutine:
ch := make(chan string)
go tcpSender(ch)
Create a value of *RestHandler with the channel and register it as the handler:
http.Handle("/rcvtelegram", &RestHandler{ch:ch})
Answered By – Kyle Jones
Answer Checked By – Mildred Charles (GoLangFix Admin)