|
1 | 1 | package application
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
| 5 | + "embed" |
4 | 6 | "fmt"
|
| 7 | + "html/template" |
5 | 8 | "net/http"
|
| 9 | + "strings" |
6 | 10 |
|
7 | 11 | "github.com/factorysh/microdensity/version"
|
| 12 | + "github.com/yuin/goldmark" |
| 13 | + "go.uber.org/zap" |
8 | 14 | )
|
9 | 15 |
|
10 |
| -// HomeHandle display the home page |
11 |
| -func HomeHandler(w http.ResponseWriter, _ *http.Request) { |
12 |
| - w.Header().Set("content-type", "text/plain") |
13 |
| - w.Write([]byte(` |
| 16 | +var ( |
| 17 | + // used to ensure embed import |
| 18 | + _ embed.FS |
| 19 | + //go:embed templates/HELP.md |
| 20 | + helpTemplate string |
| 21 | +) |
| 22 | + |
| 23 | +func acceptsHTML(r *http.Request) bool { |
| 24 | + accepts, found := r.Header["Accept"] |
| 25 | + if !found { |
| 26 | + return false |
| 27 | + } |
| 28 | + |
| 29 | + for _, h := range accepts { |
| 30 | + if strings.Contains(h, "text/html") { |
| 31 | + return true |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + return false |
| 36 | +} |
| 37 | + |
| 38 | +// HomeHandler display the home page |
| 39 | +func (a *Application) HomeHandler() http.HandlerFunc { |
| 40 | + return func(w http.ResponseWriter, r *http.Request) { |
| 41 | + l := a.logger.With( |
| 42 | + zap.String("path", "home"), |
| 43 | + ) |
| 44 | + |
| 45 | + // if you ask for something that is not html |
| 46 | + // nice geeky ascii art |
| 47 | + if !acceptsHTML(r) { |
| 48 | + w.Header().Set("content-type", "text/plain") |
| 49 | + w.Write([]byte(` |
14 | 50 | _ _ _
|
15 | 51 | ___| |__ ___ ___| | __ _ __ ___ _ _ __ _____| |__
|
16 | 52 | / __| '_ \ / _ \/ __| |/ / | '_ ' _ \| | | | \ \ /\ / / _ \ '_ \
|
17 | 53 | | (__| | | | __/ (__| < | | | | | | |_| | \ V V / __/ |_) |
|
18 | 54 | \ ___|_| |_|\___|\___|_|\_\ |_| |_| |_|\__, | \_/\_/ \___|_.__/
|
19 |
| - |___/ |
| 55 | + |___/ |
20 | 56 | `))
|
21 |
| - fmt.Fprintf(w, "Version: %s", version.Version()) |
| 57 | + fmt.Fprintf(w, "Version: %s", version.Version()) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + // text/html requests sends a documentation file |
| 62 | + template, err := template.New("help").Parse(helpTemplate) |
| 63 | + if err != nil { |
| 64 | + l.Error("template", zap.Error(err)) |
| 65 | + w.WriteHeader(http.StatusInternalServerError) |
| 66 | + return |
| 67 | + } |
| 68 | + |
| 69 | + var buffer bytes.Buffer |
| 70 | + |
| 71 | + template.Execute(&buffer, a.Services) |
| 72 | + |
| 73 | + err = goldmark.Convert(buffer.Bytes(), w) |
| 74 | + if err != nil { |
| 75 | + l.Error("markdown convert", zap.Error(err)) |
| 76 | + w.WriteHeader(http.StatusInternalServerError) |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + w.Header().Set("content-type", "text/html") |
| 81 | + } |
22 | 82 | }
|
0 commit comments