'Call TCP send (net package) from http request function

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!

go


Solution 1:[1]

Based on above proposal I built it this way:

type TcpHandler struct {
    connection net.Conn
}

Then defined a custom HTTP Handler:

func (t TcpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {...}

Then registered it with the existing TCP connection in main():

httpTcpHandler := TcpHandler{connection: conn}
mux := http.NewServeMux()
mux.Handle("/rcvtelegram", httpTcpHandler)
go startHttpServer(httpPort, mux)

Works as it should! I like programming in Go more and more ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Skye