...
1 package serverx
2
3 import (
4 "mime"
5 "net/http"
6 "strings"
7
8 "github.com/ory/x/stringslice"
9 "github.com/ory/x/stringsx"
10 )
11
12 func matchesContentTypes(r *http.Request, mimetypes []string) bool {
13 contentType := stringsx.Coalesce(r.Header.Get("Content-type"), "application/octet-stream")
14
15 for _, v := range strings.Split(contentType, ",") {
16 t, _, err := mime.ParseMediaType(v)
17 if err != nil {
18 break
19 }
20 if stringslice.Has(mimetypes, t) {
21 return true
22 }
23 }
24 return false
25 }
26
27
28 var DefaultNotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
29 w.WriteHeader(http.StatusNotFound)
30
31 if matchesContentTypes(r, []string{
32 "text/html",
33 "application/xhtml+xml",
34 "application/xml",
35 }) {
36 w.Header().Set("Content-Type", "text/html")
37 _, _ = w.Write([]byte(`<!DOCTYPE html>
38 <html lang="en">
39 <head>
40 <meta charset="UTF-8">
41 <title>404 - Route not found</title>
42 <style>*{transition:all .6s}html{height:100%}body{font-family:sans-serif;color:#888;margin:0}#main{display:table;width:100%;height:100vh;text-align:center}.fof{display:table-cell;vertical-align:middle}.fof h1{font-size:50px;display:inline-block;padding-right:12px;margin-bottom:12px;animation:type .5s alternate infinite}@keyframes type{from{box-shadow:inset -3px 0 0 #888}to{box-shadow:inset -3px 0 0 transparent}}</style>
43 </head>
44 <body translate="no">
45 <div id="main">
46 <div class="fof">
47 <h1>Error 404</h1>
48 <p>The requested route does not exist. Make sure you are using the right path, domain, and port.</p>
49 </div>
50 </div>
51 </body>
52 </html>`))
53 return
54 } else if matchesContentTypes(r, []string{
55 "text/plain",
56 }) {
57 w.Header().Set("Content-Type", "text/plain")
58 _, _ = w.Write([]byte(`Error 404 - The requested route does not exist. Make sure you are using the right path, domain, and port.`))
59 return
60 }
61
62 w.Header().Set("Content-Type", "application/json")
63 _, _ = w.Write([]byte(`{"error": "Error 404 - The requested route does not exist. Make sure you are using the right path, domain, and port."}`))
64 })
65
View as plain text