Serve index.html directly without template (#539)

Remove not needed template functions
This commit is contained in:
Anbraten 2021-11-26 01:12:44 +01:00 committed by GitHub
parent fb333a3b1b
commit 65e10d46b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 5 additions and 198 deletions

View file

@ -1,112 +0,0 @@
// Copyright 2018 Drone.IO Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"strings"
"golang.org/x/net/html"
)
// default func map with json parser.
var funcMap = template.FuncMap{
"json": func(v interface{}) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
}
// helper function creates a new template from the text string.
func mustCreateTemplate(text string) *template.Template {
templ, err := createTemplate(text)
if err != nil {
panic(err)
}
return templ
}
// helper function creates a new template from the text string.
func createTemplate(text string) (*template.Template, error) {
templ, err := template.New("_").Funcs(funcMap).Parse(partials)
if err != nil {
return nil, err
}
return templ.Parse(
injectPartials(text),
)
}
// helper function that parses the html file and injects
// named partial templates.
func injectPartials(s string) string {
w := new(bytes.Buffer)
r := bytes.NewBufferString(s)
t := html.NewTokenizer(r)
for {
tt := t.Next()
if tt == html.ErrorToken {
break
}
if tt == html.CommentToken {
txt := string(t.Text())
txt = strings.TrimSpace(txt)
seg := strings.Split(txt, ":")
if len(seg) == 2 && seg[0] == "drone" {
fmt.Fprintf(w, "{{ template %q . }}", seg[1])
continue
}
}
w.Write(t.Raw())
}
return w.String()
}
const partials = `
{{define "user"}}
{{ if .user }}
<script>
window.DRONE_USER = {{ json .user }};
window.DRONE_SYNC = {{ .syncing }};
</script>
{{ end }}
{{end}}
{{define "csrf"}}
{{ if .csrf -}}
<script>
window.DRONE_CSRF = "{{ .csrf }}"
</script>
{{- end }}
{{end}}
{{define "version"}}
<script>
window.DRONE_VERSION = {{ .version }};
</script>
<meta name="version" content="{{ .version }}">
{{end}}
{{define "docs"}}
{{ if .docs -}}
<script>
window.DRONE_DOCS = "{{ .docs }}"
</script>
{{- end }}
{{end}}
`

View file

@ -1,48 +0,0 @@
// Copyright 2018 Drone.IO Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"testing"
)
func Test_injectPartials(t *testing.T) {
got, want := injectPartials(before), after
if got != want {
t.Errorf("Want html %q, got %q", want, got)
}
}
var before = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- drone:version -->
<!-- drone:user -->
<!-- drone:csrf -->
<link rel="shortcut icon" href="/favicon.png"></head>
<body>
</html>`
var after = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
{{ template "version" . }}
{{ template "user" . }}
{{ template "csrf" . }}
<link rel="shortcut icon" href="/favicon.png"></head>
<body>
</html>`

View file

@ -18,7 +18,6 @@ import (
"context" "context"
"crypto/md5" "crypto/md5"
"fmt" "fmt"
"html/template"
"net/http" "net/http"
"time" "time"
@ -26,8 +25,6 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/woodpecker-ci/woodpecker/server/model" "github.com/woodpecker-ci/woodpecker/server/model"
"github.com/woodpecker-ci/woodpecker/shared/token"
"github.com/woodpecker-ci/woodpecker/version"
"github.com/woodpecker-ci/woodpecker/web" "github.com/woodpecker-ci/woodpecker/web"
) )
@ -47,16 +44,14 @@ func New(opt ...Option) Endpoint {
return &website{ return &website{
fs: web.HttpFS(), fs: web.HttpFS(),
opts: opts, opts: opts,
tmpl: mustCreateTemplate( data: web.MustLookup("index.html"),
string(web.MustLookup("index.html")),
),
} }
} }
type website struct { type website struct {
opts *Options opts *Options
fs http.FileSystem fs http.FileSystem
tmpl *template.Template data []byte
} }
func (w *website) Register(mux *gin.Engine) { func (w *website) Register(mux *gin.Engine) {
@ -68,33 +63,11 @@ func (w *website) Register(mux *gin.Engine) {
} }
func (w *website) handleIndex(rw http.ResponseWriter, r *http.Request) { func (w *website) handleIndex(rw http.ResponseWriter, r *http.Request) {
var csrf string
var user, _ = ToUser(r.Context())
if user != nil {
csrf, _ = token.New(
token.CsrfToken,
user.Login,
).Sign(user.Hash)
}
var syncing bool
if user != nil {
syncing = time.Unix(user.Synced, 0).Add(w.opts.sync).Before(time.Now())
}
params := map[string]interface{}{
"user": user,
"csrf": csrf,
"syncing": syncing,
"version": version.String(),
}
rw.Header().Set("Content-Type", "text/html; charset=UTF-8") rw.Header().Set("Content-Type", "text/html; charset=UTF-8")
if err := w.tmpl.Execute(rw, params); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
log.Error().Err(err).Msg("execute template")
return
}
rw.WriteHeader(200) rw.WriteHeader(200)
if _, err := rw.Write(w.data); err != nil {
log.Error().Err(err).Msg("can not write index.html")
}
} }
func setupCache(h http.Handler) http.Handler { func setupCache(h http.Handler) http.Handler {
@ -116,12 +89,6 @@ func WithUser(c context.Context, user *model.User) context.Context {
return context.WithValue(c, userKey, user) return context.WithValue(c, userKey, user)
} }
// ToUser returns a user from the context.
func ToUser(c context.Context) (*model.User, bool) {
user, ok := c.Value(userKey).(*model.User)
return user, ok
}
type key int type key int
const userKey key = 0 const userKey key = 0