Answer the question
In order to leave comments, you need to log in
How to add your own method to http.ResponseWriter?
There is a route (mux router):
router.HandleFunc("", controllerPost).Methods(http.MethodPost)
func controllerPost(response http.ResponseWriter, request *http.Request)
type HttpResponse struct {
http.ResponseWriter
}
func (r *HttpResponse) Send(data string, statusCode int){
r.ResponseWriter.WriteHeader(statusCode)
_, err := r.ResponseWriter.Write([]byte(data))
if err != nil {
Logger.Error(err.Error())
}
return
}
func controllerPost(response HttpResponse, request *http.Request)
Cannot use 'controllerPost' (type func(response HttpResponse, request *http.Request)) as the type func(http.ResponseWriter, *http.Request)
Answer the question
In order to leave comments, you need to log in
This is because you are changing the type of the function's first argument.
I think it’s worth saying right away that if the task is to log errors in sending responses, it’s better to make a separate Middleware that will do this. Both options described below will be extremely unsuccessful for solving such a problem.
There are at least two options for solving this problem:
1st and easiest - make the functions you need so that they accept an interface, for example:
func Send(w http.ResponseWriter, data string, statusCode int){
// тут ваша реализация
w.WriteHeader(statusCode)
_, err := w.Write([]byte(data))
if err != nil {
Logger.Error(err.Error())
}
return
}
func controllerPost(w http.ResponseWriter, request *http.Request) {
Send(w, data, code)
}
func respondHTML(w http.ResponseWriter, statusCode int, body string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(statusCode)
w.Write([]byte(body))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question