[PATCH pages.sr.ht] Respond with 404 statusCode for notFound page
Export this patch
---
Ths patch I submitted for 404 pages did not handle statusCode correctly.
Sorry about that. I created another patch to fix it. But I saw that we
moved onto using http.ServeContent, which I believe, does not allow
specifying statusCode explicitly. Here's my attempt at handling
statusCode with 404 pages.
I'm not entirely sure about how readable this code is. I'm open for
suggestions.
server.go | 28 ++++++++++++++++++++--------
1 file changed, 20 insertions(+), 8 deletions(-)
diff --git a/server.go b/server.go
index 6d73960..e8bd85f 100644
--- a/server.go
+++ b/server.go
@@ -182,7 +182,7 @@ func ServeHTTP(conf ini.File, db *sql.DB, mc *minio.Client) *http.Server {
strings.Join(sandbox, " ")))
var version string
- var notFound *string
+ var notFoundPath *string
ctx := database.Context(r.Context(), db)
if err := database.WithTx(ctx, &sql.TxOptions{
ReadOnly: true,
@@ -193,7 +193,7 @@ func ServeHTTP(conf ini.File, db *sql.DB, mc *minio.Client) *http.Server {
FROM sites
WHERE domain = $1 AND protocol = 'https';
`, r.Host)
- if err := row.Scan(&version, ¬Found); err != nil {
+ if err := row.Scan(&version, ¬FoundPath); err != nil {
return err
}
return nil
@@ -209,13 +209,14 @@ func ServeHTTP(conf ini.File, db *sql.DB, mc *minio.Client) *http.Server {
path.Join(r.URL.Path, "index.html"),
}
- if notFound != nil {
- paths = append(paths, *notFound)
+ if notFoundPath != nil {
+ paths = append(paths, *notFoundPath)
}
var s3path string
var object *minio.Object
var objectInfo minio.ObjectInfo
+ found := false
for _, cand := range paths {
s3path = path.Join(prefix, "sites", r.Host, version, cand)
var err error
@@ -227,15 +228,26 @@ func ServeHTTP(conf ini.File, db *sql.DB, mc *minio.Client) *http.Server {
if err != nil {
panic(err)
}
+ found = notFoundPath == nil || cand != *notFoundPath
break
}
- if object == nil {
- http.Error(w, "404 Page not found\n", 404)
+ defer object.Close()
+ if !found {
+ if notFoundPath == nil {
+ http.Error(w, "404 Page not found\n", http.StatusNotFound)
+ return
+ }
+ mimetype := mime.TypeByExtension(path.Ext(*notFoundPath))
+ if mimetype != "" {
+ w.Header().Add("Content-Type", mimetype)
+ }
+ w.WriteHeader(http.StatusNotFound)
+ if _, err := io.Copy(w, object); err != nil {
+ log.Println(err.Error())
+ }
return
}
-
- defer object.Close()
http.ServeContent(w, r, s3path, objectInfo.LastModified, object)
}))
return srv
--
2.35.1
pages.sr.ht/patches: SUCCESS in 1m41s
[Respond with 404 statusCode for notFound page][0] from [Dhruvin Gandhi][1]
[0]: https://lists.sr.ht/~sircmpwn/sr.ht-dev/patches/29873
[1]: mailto:contact@dhruvin.dev
✓ #705042 SUCCESS pages.sr.ht/patches/alpine.yml https://builds.sr.ht/~sircmpwn/job/705042
✓ #705043 SUCCESS pages.sr.ht/patches/archlinux.yml https://builds.sr.ht/~sircmpwn/job/705043
Thanks!
To git@git.sr.ht:~sircmpwn/pages.sr.ht
66017d5..a36bcab master -> master