package handler import ( "database/sql" "encoding/json" "errors" "fmt" "net/http" "strings" ) // GetIncident responds to the link generated in the response to a New Snow func (h *Handler) GetIncident(w http.ResponseWriter, r *http.Request) { h.Logger.Debug("GetIncident Request received", "method", r.Method, "url", r.URL, "path", r.URL.Path, "query", r.URL.Query()) ctx := r.Context() path := r.URL.Path // Expected format: /api/now/table/incident/{id} parts := strings.Split(path, "/") h.Logger.Debug("Request path", "parts", parts) // Parse and write query parameters query := r.URL.Query() if len(query) == 0 { h.Logger.Debug("No query parameters.") } else { //fmt.Fprintln(w, "Query parameters:") for key, values := range query { for _, value := range values { h.Logger.Debug("Query Paramater", "key", key, "value", value) } } } if len(parts) == 6 && strings.HasPrefix(path, "/api/now/table/incident/") { // Handle the specific 'number' query parameter number := query.Get("number") if number != "" { h.Logger.Debug("GetIncident called for specific incident number", "number", number) // Query record from database and return that } else { // Requested a single incident id := parts[5] // Extract {id} h.Logger.Debug("GetIncident called for specific incident", "id", id) incResult, err := h.Database.Queries().GetIncident(ctx, nullStr(number)) if err != nil { if errors.Is(err, sql.ErrNoRows) { h.Logger.Debug("No incident record found", "number", number) } else { h.Logger.Error("Unable to query database for incident number", "error", err) //return err } } b, err := json.Marshal(incResult) if err != nil { h.Logger.Error("Unable to convert database record into json", "error", err) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode(map[string]string{ "status": "ERROR", "message": fmt.Sprintf("Unable to convert database record into json: '%s'", err), }) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, string(b)) return } } else if strings.HasPrefix(path, "/api/now/table/incident") { h.Logger.Debug("GetIncident called for list of incidents") w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "{\"result\": [{}]}") } // TODO - provide an incident list if necessary }