Hi George, here is the code:
The Mux Router code:
router.HandleFunc(/api/{Entity}, functions.GetPostMortemDiag).Methods(GET, POST, PUT, DELETE)|
router.HandleFunc(/api/{entity}/{entityNumber}, functions.GetPostMortemDiag).Methods(GET, PUT)|]router.HandleFunc(/api/{entity}/{entityId}/{entity}, functions.GetPostMortemDiag).Methods(GET)
Handler Function code:
func GetPostMortemDiag(w http.ResponseWriter, r *http.Request) {
log.Println("INFO - GetPostMortemDiag(): Entering GetPostMortem Diag function")
api_base_url = os.Getenv("MYAPP_POSTMORTEM_API") + r.URL.Path
// validate request auth
retcode := CheckRequestAuth(w, r, "MYAPP")
if retcode == 0 {
log.Println("INFO - GetPostMortemDiag(): Request auth is successful")
} else {
log.Println("ERR - GetPostMortemDiag(): Request auth is not successful")
return
}
// Steps to Call the backend API start now
// build the url further with the parameters from request
// Call the backend API with the built urls
query := r.URL.Query() // get the query from the request
api_url, err := url.Parse(api_base_url)
if err != nil {
log.Println("ERR - GetPgDiag(): Could not parse the backend API base URL: ", err.Error())
w.WriteHeader(http.StatusUnprocessableEntity)
//not sure about the above status code
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "Could not parse the backend API base URL, please correct the URL or contact the administrator"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Println("WARN - GetPgDiag(): Error happened in JSON marshal for failed backend-api-parse response. Err: %s", err)
}
w.Write(jsonResp)
return
}
api_url.RawQuery = query.Encode() // builds further the URL struct adding the query
_, err = url.Parse(api_url.String())
if err != nil {
log.Println("ERR - GetPgDiag(): Could not parse the query to backend API base URL: ", err.Error())
w.WriteHeader(http.StatusUnprocessableEntity)
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "Could not parse query to the backend API base URL, please correct the query or contact the administrator"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Println("WARN - GetPgDiag(): Error happened in JSON marshal for failed backend-api-query-parse response. Err: %s", err)
}
w.Write(jsonResp)
return
}
log.Println("INFO - GetPostMortemDiag(): Calling API endpoint", api_url)
timeout, err = strconv.Atoi(os.Getenv("MYAPP_POSTMORTEM_API_TIMEOUT"))
if err != nil {
log.Println("WARN - GetPostMortemDiag(): MYAPP_POSTMORTEM_API_TIMEOUT environment variable not set or erroneous, Using default value ", err)
timeout = default_timeout
}
token = SetJwt(false, "sgfr") // false means refresh=false - that is, DO NOT force a refresh
if token == "" {
log.Println("ERR - GetPostMortemDiag(): ForgeRock Token Validation failed: ")
w.WriteHeader(http.StatusUnauthorized)
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "ForgeRock Token Validation failed , Please contact the administrator"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Println("WARN - GetPostMortemDiag(): Error happened in JSON marshal for Unauthorized response. Err: %s", err)
}
w.Write(jsonResp)
return
}
if r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE" {
if r.URL.Path == "/api/images-upload" {
UploadImages(w, r)
return
} else {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
err_text := fmt.Sprintf("ERR - CallPostMortemAPI(): Error reading request body: %v", err)
log.Printf(err_text)
http.Error(w, err_text, http.StatusBadRequest)
return
}
BodyData := string(body)
myReader = strings.NewReader(BodyData)
}
}
log.Println("myReader", reflect.TypeOf(myReader))
if myReader != nil {
log.Println("DEBUG - CallPostMortemAPI() : Request has a body")
req, err = http.NewRequest(r.Method, api_url.String(), myReader)
} else {
log.Println("DEBUG - CallPostMortemAPI() : Request does not have a body")
req, err = http.NewRequest(r.Method, api_url.String(), nil)
}
if err != nil {
log.Println("ERR - GetPostMortemDiag(): Error while creating request to the backend API: "+api_url.String(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "Error while creating request to the backend API" + api_url.String()
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Println("WARN - GetPostMortemDiag(): Error happened in JSON marshal for Unauthorized response. Err: %s", err)
}
w.Write(jsonResp)
return
}
req.Header.Set("Authorization", "Bearer "+token)
if os.Getenv("ENV") == "LOCAL" {
req.Header.Set("Consumer-Key", os.Getenv("SGFR-CONSUMER-KEY-POSTMORTEM"))
} else {
req.Header.Set("Consumer-Key", GetDataFromVault(SGFR_CONSUMER_KEY_VALUE))
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{
Timeout: time.Second * time.Duration(timeout),
}
response, err := client.Do(req)
if err != nil {
log.Println("ERR - CallPostMortemAPI(): API Call failed: "+api_url.String(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "API Call failed: " + api_url.String()
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Println("WARN - CallPostMortemAPI(): Error happened in JSON marshal for Unauthorized response. Err: %s", err)
}
//tbd - handle error condition
w.Write(jsonResp)
return
}
w.WriteHeader(response.StatusCode)
defer response.Body.Close()
w.Header().Set("Content-Type", "application/json")
log.Println("INFO - GetPostMortemDiag(): Response code from URL: ", response.StatusCode)
b, err := io.ReadAll(response.Body)
// fmt.Fprint(w, string(b))
w.Write(b)
}
** React Code **
They are axios calls to different endpoints - to different endpoints served my mux, and called from one React page. The problem is that some/all of those multiple calls are showing the same response - which is the response for one of those calls.
As you see in the mux-router code, {entity} makes it easier to overload one mux router entry to serve more than one endpoint. However, even without such {entity} parameterization, if we made separate mux lines for each endpoint, and separate handler function for each such endpoint, the bahaviour has been the same.