I'm trying to get my web server to accept different socket calls in one function. My code looks like this:
Go:
func handler(w io.Writer, r *io.ReadCloser) {
//do something
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
I get the error:
cannot use handler (type func(io.Writer, *io.ReadCloser)) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc
How do I implement this?
As shown in the article "Writing Web Applications", the example for HandleFunc is:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
You cannot replace a r *http.Request
by an r *io.ReadCloser
.
You would need to delegate that call in a wrapper, as suggested in this thread:
func wrappingHandler(w http.ResponseWriter, r *http.Request){
handler(w, r.Body)
}
func main() {
http.HandleFunc("/", wrappingHandler)
http.ListenAndServe(":8080", nil)
}
Or simply modify your handler:
func handler(w http.ResponseWriter, r *http.Request) {
rb := r.Body
//do something with rb instead of r
}