Skip to content

Commit

Permalink
fix(download): write error as problem details
Browse files Browse the repository at this point in the history
  • Loading branch information
ncarlier committed Aug 25, 2023
1 parent 0d0c034 commit a9f7a4e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
8 changes: 5 additions & 3 deletions pkg/api/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@ import (
"github.com/ncarlier/readflow/pkg/service"
)

var downloadProblem = "unable to download article"

// download is the handler for downloading articles.
func download() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/articles/")
if id == "" {
http.Error(w, "missing article ID", http.StatusBadRequest)
helper.WriteProblemDetail(w, downloadProblem, "missing article ID", http.StatusBadRequest)
return
}
idArticle, ok := helper.ConvGQLStringToUint(id)
if !ok {
http.Error(w, "invalid article ID", http.StatusBadRequest)
helper.WriteProblemDetail(w, downloadProblem, "invalid article ID", http.StatusBadRequest)
return
}
// Extract and validate token parameter
Expand All @@ -32,7 +34,7 @@ func download() http.Handler {
// Archive the article
asset, err := service.Lookup().DownloadArticle(r.Context(), idArticle, format)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.WriteProblemDetail(w, downloadProblem, err.Error(), http.StatusInternalServerError)
return
}

Expand Down
25 changes: 25 additions & 0 deletions pkg/helper/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package helper

import (
"encoding/json"
"net/http"
)

type problemObject struct {
Title string `json:"title"`
Detail string `json:"detail"`
Status int `json:"status"`
}

// WriteProblemDetail write error as JSON Problem Details format
func WriteProblemDetail(w http.ResponseWriter, title string, detail string, status int) {
err := problemObject{
Title: title,
Detail: detail,
Status: status,
}
w.Header().Set("Content-Type", "application/problem+json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
json.NewEncoder(w).Encode(err)
}

0 comments on commit a9f7a4e

Please sign in to comment.