handleDialIndex handles the "GET /dials" route. This route can optionally accept filter arguments and outputs a list of all dials that the current user is a member of. The endpoint works with HTML, JSON, & CSV formats.
(w http.ResponseWriter, r *http.Request)
| 47 | // |
| 48 | // The endpoint works with HTML, JSON, & CSV formats. |
| 49 | func (s *Server) handleDialIndex(w http.ResponseWriter, r *http.Request) { |
| 50 | // Parse optional filter object. |
| 51 | var filter wtf.DialFilter |
| 52 | switch r.Header.Get("Content-type") { |
| 53 | case "application/json": |
| 54 | if err := json.NewDecoder(r.Body).Decode(&filter); err != nil { |
| 55 | Error(w, r, wtf.Errorf(wtf.EINVALID, "Invalid JSON body")) |
| 56 | return |
| 57 | } |
| 58 | default: |
| 59 | filter.Offset, _ = strconv.Atoi(r.URL.Query().Get("offset")) |
| 60 | filter.Limit = 20 |
| 61 | } |
| 62 | |
| 63 | // Fetch dials from database. |
| 64 | dials, n, err := s.DialService.FindDials(r.Context(), filter) |
| 65 | if err != nil { |
| 66 | Error(w, r, err) |
| 67 | return |
| 68 | } |
| 69 | |
| 70 | // Render output based on HTTP accept header. |
| 71 | switch r.Header.Get("Accept") { |
| 72 | case "application/json": |
| 73 | w.Header().Set("Content-type", "application/json") |
| 74 | if err := json.NewEncoder(w).Encode(findDialsResponse{ |
| 75 | Dials: dials, |
| 76 | N: n, |
| 77 | }); err != nil { |
| 78 | LogError(r, err) |
| 79 | return |
| 80 | } |
| 81 | |
| 82 | case "text/csv": |
| 83 | w.Header().Set("Content-type", "text/csv") |
| 84 | enc := csv.NewDialEncoder(w) |
| 85 | for _, dial := range dials { |
| 86 | if err := enc.EncodeDial(dial); err != nil { |
| 87 | LogError(r, err) |
| 88 | return |
| 89 | } |
| 90 | } |
| 91 | if err := enc.Close(); err != nil { |
| 92 | LogError(r, err) |
| 93 | return |
| 94 | } |
| 95 | |
| 96 | default: |
| 97 | tmpl := html.DialIndexTemplate{Dials: dials, N: n, Filter: filter, URL: *r.URL} |
| 98 | tmpl.Render(r.Context(), w) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // findDialsResponse represents the output JSON struct for "GET /dials". |
| 103 | type findDialsResponse struct { |
nothing calls this directly
no test coverage detected