diff options
Diffstat (limited to 'cmd/web/handlers.go')
-rw-r--r-- | cmd/web/handlers.go | 62 |
1 files changed, 38 insertions, 24 deletions
diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index d4ac91c..1f3a58f 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -1,15 +1,14 @@ package main import ( + "errors" "fmt" + "html/template" "net/http" - "text/template" -) - -func (app *application) notFound(w http.ResponseWriter) { - http.Error(w, http.StatusText(401), 401) -} + "strconv" + "github.com/yulqen/ded-go-core/internal/models" +) func (app *application) listOrganisation(w http.ResponseWriter, r *http.Request) { files := []string{ @@ -31,10 +30,10 @@ func (app *application) listOrganisation(w http.ResponseWriter, r *http.Request) } func (app *application) home(w http.ResponseWriter, r *http.Request) { - // Check if the current request URL path exactly matches "/". If it doesn't, use - // the http.NotFound() function to send a 404 response to the client. - // Importantly, we then return from the handler. If we don't return the handler - // would keep executing. + // Check if the current request URL path exactly matches "/". If it doesn't, use + // the http.NotFound() function to send a 404 response to the client. + // Importantly, we then return from the handler. If we don't return the handler + // would keep executing. if r.URL.Path != "/" { app.notFound(w) return @@ -59,24 +58,39 @@ func (app *application) home(w http.ResponseWriter, r *http.Request) { } func (app *application) organisationView(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("This is an organisation")) + id, err := strconv.Atoi(r.URL.Query().Get("id")) + if err != nil || id < 1 { + app.notFound(w) + return + } + + o, err := app.organisations.Get(id) + if err != nil { + if errors.Is(err, models.ErrNoRecord) { + app.notFound(w) + } else { + app.serverError(w, r, err) + } + return + } + fmt.Fprintf(w, "%+v", o) } func (app *application) organisationCreate(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - w.Header().Set("Allow", http.MethodPost) - app.clientError(w, http.StatusMethodNotAllowed) - return - } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + app.clientError(w, http.StatusMethodNotAllowed) + return + } - // Dummy data - name := "Test Organisation" + // Dummy data + name := "Test Organisation" - id, err := app.organisations.Insert(name) - if err != nil { - app.serverError(w, r, err) - return - } + id, err := app.organisations.Insert(name) + if err != nil { + app.serverError(w, r, err) + return + } - http.Redirect(w, r, fmt.Sprintf("/organisation/view?id=%d", id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("/organisation/view?id=%d", id), http.StatusSeeOther) } |