func (h *HTTPServer) handleHello(w http.ResponseWriter, r http.Request) {
}
Implement NewDeliveryHoursServer correctly
Assistant
To implement NewDeliveryHoursServer correctly, you need to create the http.Server and set up the HTTP handlers before returning the initialized HTTPServer instance.
Here is a more complete example:
go
User
│ │ └╴E cannot use httpServer.handleHello (value of type func(w http.ResponseWriter, r http.Request)) as http.Handler value in argument to mux.Handle: func(w http.ResponseWriter, r http.Request) does not implement http.Handler (missing method ServeHTTP) compiler (InvalidIfaceAssign) [20, 23]
Assistant
The error:
code
cannot use httpServer.handleHello (value of type func(w http.ResponseWriter, r http.Request)) as http.Handler value in argument to mux.Handle: func(w http.ResponseWriter, r http.Request) does not implement http.Handler (missing method ServeHTTP)
package main
import (
"net/http"
)
type DeliveryHoursComposer interface {
// define the interface methods here
}
type HTTPServer struct {
deliveryHoursComposer DeliveryHoursComposer
server *http.Server
}
func (h *HTTPServer) handleHello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world!"))
}
func NewDeliveryHoursServer(deliveryHoursComposer DeliveryHoursComposer) *HTTPServer {
h := &HTTPServer{
deliveryHoursComposer: deliveryHoursComposer,
}
mux := http.NewServeMux()
mux.HandleFunc("/hello", h.handleHello)
h.server = &http.Server{
Addr: ":8080", // or any address/port you want
Handler: mux,
}
return h
}
func main() {
// Example of usage:
var composer DeliveryHoursComposer // populate this
server := NewDeliveryHoursServer(composer)
server.server.ListenAndServe()
}
Explanation:
You create an http.ServeMux and register your handler method(s) on it.
You create an http.Server wrapping that ServeMux.
Then assign the server to your struct and return.
Also, note the method signature fix: handleHello should take a pointer receiver (*HTTPServer) and the second parameter should be a pointer to http.Request (i.e., *http.Request), not http.Request.
In short, fix your handleHello signature:
go
func (h *HTTPServer) handleHello(w http.ResponseWriter, r *http.Request) {
// your handler code
}
Change to:
go
func (h *HTTPServer) handleHello(w http.ResponseWriter, r *http.Request) {
// your handler code
}
indicates that you are trying to use mux.Handle() with a handler function, but mux.Handle() expects an http.Handler (an interface), not a function.
In Go's standard library:
mux.Handle(pattern string, handler http.Handler) expects an http.Handler (an interface).
mux.HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) expects a function.
Your handleHello method is a function with signature:
go
func (h *HTTPServer) handleHello(w http.ResponseWriter, r http.Request){
// ...
}