Below is the generic function to handle http request
func Process[Req GoLibRequest, Resp GoLibResponse](w http.ResponseWriter, r *http.Request, processFunc func(request GoLibRequest, response *GoLibResponse) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
request := GoLibRequest{MsgId: GetMsgID()}
response := GoLibResponse{MsgId: GetMsgID()}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
Logger.Errorf("Decoding body failed: %v", err)
resErr := NewHTTPError(err, 400, "Bad request : invalid JSON.", "EGN002")
response.Error = resErr
json.NewEncoder(w).Encode(response)
return
}
resErr := processFunc(request, &response)
if resErr != nil {
Logger.Errorf("Unable to process request: %v", resErr)
response.Error = resErr
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(200)
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("Encoding response failed: %v", err)
}
}
}
how do i pass this function to mux router properly .
currently passing as below
sm := http.NewServeMux()
sm.HandleFunc(“/login”, lib.Process(ProcessLogin))
s := &http.Server{
Addr: ":9091",
Handler: sm,
IdleTimeout: 120 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
}
go func() {
err := s.ListenAndServe()
if err != nil {
lib.Logger.Error(err)
}
}()