handleDialCreate handles the "POST /dials" and "POST /dials/new" route. It reads & writes data using with HTML or JSON.
(w http.ResponseWriter, r *http.Request)
| 156 | // handleDialCreate handles the "POST /dials" and "POST /dials/new" route. |
| 157 | // It reads & writes data using with HTML or JSON. |
| 158 | func (s *Server) handleDialCreate(w http.ResponseWriter, r *http.Request) { |
| 159 | // Unmarshal data based on HTTP request's content type. |
| 160 | var dial wtf.Dial |
| 161 | switch r.Header.Get("Content-type") { |
| 162 | case "application/json": |
| 163 | if err := json.NewDecoder(r.Body).Decode(&dial); err != nil { |
| 164 | Error(w, r, wtf.Errorf(wtf.EINVALID, "Invalid JSON body")) |
| 165 | return |
| 166 | } |
| 167 | default: |
| 168 | dial.Name = r.PostFormValue("name") |
| 169 | } |
| 170 | |
| 171 | // Create dial in the database. |
| 172 | err := s.DialService.CreateDial(r.Context(), &dial) |
| 173 | |
| 174 | // Write new dial content to response based on accept header. |
| 175 | switch r.Header.Get("Accept") { |
| 176 | case "application/json": |
| 177 | if err != nil { |
| 178 | Error(w, r, err) |
| 179 | return |
| 180 | } |
| 181 | |
| 182 | w.Header().Set("Content-type", "application/json") |
| 183 | w.WriteHeader(http.StatusCreated) |
| 184 | if err := json.NewEncoder(w).Encode(dial); err != nil { |
| 185 | LogError(r, err) |
| 186 | return |
| 187 | } |
| 188 | |
| 189 | default: |
| 190 | // If we have an internal error, display the standard error page. |
| 191 | // Otherwise it's probably a validation error so we can display the |
| 192 | // error on the edit page with the user's dial data that was passed in. |
| 193 | if wtf.ErrorCode(err) == wtf.EINTERNAL { |
| 194 | Error(w, r, err) |
| 195 | return |
| 196 | } else if err != nil { |
| 197 | tmpl := html.DialEditTemplate{Dial: &dial, Err: err} |
| 198 | tmpl.Render(r.Context(), w) |
| 199 | return |
| 200 | } |
| 201 | |
| 202 | // Set a message to the user and redirect to the dial's new page. |
| 203 | SetFlash(w, "Dial successfully created.") |
| 204 | http.Redirect(w, r, fmt.Sprintf("/dials/%d", dial.ID), http.StatusFound) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // handleDialEdit handles the "GET /dials/:id/edit" route. This route fetches |
| 209 | // the underlying dial and renders it in an HTML form. |