-
Notifications
You must be signed in to change notification settings - Fork 9
/
welcome.go
75 lines (62 loc) · 1.67 KB
/
welcome.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package pages
import (
"embed"
"encoding/base64"
"errors"
"html/template"
"io/fs"
"log"
"net"
"net/http"
"strings"
"namespacelabs.dev/foundation/framework/runtime"
)
var (
//go:embed logo.png welcome.html.template output.css
resources embed.FS
logoBytesBase64, cssStyles string
welcomeTemplate *template.Template
)
func init() {
logoBytesBase64 = base64.StdEncoding.EncodeToString(mustRead("logo.png"))
cssStyles = string(mustRead("output.css"))
t, err := template.New("welcome.html").Parse(string(mustRead("welcome.html.template")))
if err != nil {
panic(err)
}
welcomeTemplate = t
}
type welcomeTemplateData struct {
PackageName string
Static struct {
Style template.CSS
LogoBase64 string
}
}
func WelcomePage(srv *runtime.Server) func(http.ResponseWriter, *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(200)
pkg := strings.TrimPrefix(srv.PackageName, srv.ModuleName+"/")
data := welcomeTemplateData{PackageName: pkg}
data.Static.Style = template.CSS(cssStyles)
data.Static.LogoBase64 = logoBytesBase64
if err := welcomeTemplate.Execute(rw, data); err != nil {
var opError *net.OpError
if errors.As(err, &opError) {
// Do not log network errors (e.g. connection reset by peer)
return
}
log.Printf("rendering welcome failed: %v", err)
}
}
}
func mustRead(name string) []byte {
contents, err := fs.ReadFile(resources, name)
if err != nil {
panic(err)
}
return contents
}