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!
CodePudding user response:
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})
CodePudding user response:
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