fix: fixed the wrong order of rendering.

This commit is contained in:
Andrey Parhomenko 2024-05-18 01:55:02 +05:00
parent 502cfbe390
commit 625d73689a
9 changed files with 85 additions and 37 deletions

View file

@ -48,6 +48,7 @@ func (h *Handler) ServeHTTP(
w http.ResponseWriter, w http.ResponseWriter,
r *http.Request, r *http.Request,
) { ) {
shouldProcess := true
urlPath := r.URL.Path urlPath := r.URL.Path
// Cleaning URL path to prevent injections. // Cleaning URL path to prevent injections.
urlPath = path.Clean(urlPath) urlPath = path.Clean(urlPath)
@ -62,8 +63,12 @@ func (h *Handler) ServeHTTP(
//log.Println("pth:", urlPath, filePathTpp) //log.Println("pth:", urlPath, filePathTpp)
file, err := os.Open(filePathTpp) file, err := os.Open(filePathTpp)
if err != nil { if err != nil {
http.NotFound(w, r) shouldProcess = false
return file, err = os.Open(filePath)
if err != nil {
http.NotFound(w, r)
return
}
} }
//process := true //process := true
@ -73,25 +78,35 @@ func (h *Handler) ServeHTTP(
return return
} }
ctx := context.WithValue(r.Context(), KeyRequest, &Request{ ctx := context.WithValue(
Request: r, r.Context(),
}) KeyRequest,
&Request{
Request: r,
},
)
// Setting before the code to let it change own // Setting before the code to let it change own
// content type. // content type.
contentType := mime.TypeByExtension(urlExt) contentType := mime.TypeByExtension(urlExt)
w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Type", contentType)
processedData, err := h.pp.Process( processedData := fileData
ctx, if shouldProcess {
true, processedData, err = h.pp.Process(
filePathTpp, ctx,
fileData, true,
) filePathTpp,
if err != nil { fileData,
http.NotFound(w, r) )
log.Printf("Error: pp.Process(...): %s\n", err) if err != nil {
return http.NotFound(w, r)
log.Printf(
"Error: pp.Process(...): %s\n",
err,
)
return
}
} }
w.Write(processedData) w.Write(processedData)

View file

@ -44,10 +44,8 @@ var Tool = mtool.T("tht").Func(func(flags *mtool.Flags) {
http := immutable({ http := immutable({
request : __http_request__ request : __http_request__
}) })
__context__ := { __context__.http = http
http: http, __context__.pp = pp
pp: pp
}
import("./pre")(__context__) import("./pre")(__context__)
`) `)
}).SetPostCode(func(ctx context.Context) []byte { }).SetPostCode(func(ctx context.Context) []byte {

View file

@ -66,9 +66,9 @@ func (u *URL) IndexGet(
case "path" : case "path" :
return tengo.FromInterface(u.Path) return tengo.FromInterface(u.Path)
case "query" : case "query" :
return tengo.FromInterface(&Values{ return &Values{
Values: u.Query(), Values: u.Query(),
}) }, nil
} }
// Nothing found. // Nothing found.

21
main.go
View file

@ -10,6 +10,7 @@ import (
type Preprocessor struct { type Preprocessor struct {
tengo *Tengo tengo *Tengo
tags [2][]byte tags [2][]byte
preTag byte
} }
// Get the new preprocessor with default options. // Get the new preprocessor with default options.
@ -20,6 +21,7 @@ func New(tengo *Tengo ) *Preprocessor {
[]byte("{{"), []byte("{{"),
[]byte("}}"), []byte("}}"),
} }
pp.preTag = '#'
return pp return pp
} }
@ -30,12 +32,12 @@ func (pp *Preprocessor) Process(
data []byte, data []byte,
) ([]byte, error) { ) ([]byte, error) {
var b bytes.Buffer var b bytes.Buffer
last := 0 preCodes := [][]byte{}
texts := [][]byte{} texts := [][]byte{}
codes := [][]byte{} codes := [][]byte{}
for { for {
idxStart := bytes.Index(data[last:], pp.tags[0]) idxStart := bytes.Index(data, pp.tags[0])
idxEnd := bytes.Index(data[last:], pp.tags[1]) idxEnd := bytes.Index(data, pp.tags[1])
//fmt.Printf("cock %d %d %d\n", last, idxStart, idxEnd) //fmt.Printf("cock %d %d %d\n", last, idxStart, idxEnd)
if idxStart < 0 { if idxStart < 0 {
if idxEnd >= 0 { if idxEnd >= 0 {
@ -43,18 +45,24 @@ func (pp *Preprocessor) Process(
What: "end tag", What: "end tag",
} }
} }
texts = append(texts, data[last:]) texts = append(texts, data)
break break
} else if idxEnd < 0 { } else if idxEnd < 0 {
return nil, UnexpectedError{ return nil, UnexpectedError{
What: "start tag", What: "start tag",
} }
} }
text := data[last:idxStart]
text := data[:idxStart]
texts = append(texts, text) texts = append(texts, text)
code := data[idxStart+len(pp.tags[0]):idxEnd] code := data[idxStart+len(pp.tags[0]):idxEnd]
codes = append(codes, code) if len(code) > 0 && code[0] == pp.preTag {
code = code[1:]
preCodes = append(preCodes, code)
} else {
codes = append(codes, code)
}
data = data[idxEnd + len(pp.tags[1]):] data = data[idxEnd + len(pp.tags[1]):]
/*if len(data) > 0 && data[0] == '\n' { /*if len(data) > 0 && data[0] == '\n' {
@ -65,6 +73,7 @@ func (pp *Preprocessor) Process(
ctx, ctx,
recompile, recompile,
filePath, filePath,
preCodes,
codes, codes,
) )
if err != nil { if err != nil {

View file

@ -5,7 +5,11 @@ htmExt := func(c){
c.pp.print(` c.pp.print(`
<!doctype html> <!doctype html>
<html><head> <html><head>
<title>Check shit</title> `)
if !is_undefined(c.title) {
c.pp.printf(`<title>%s</title>`, c.title)
}
c.pp.print(`
</head><body> </head><body>
`) `)
} }

View file

@ -1,16 +1,24 @@
{{#
__context__.title = "The example.site main page"
}}
<h1>This is the example page for the THT</h1>
{{ {{
fmt := import("fmt") fmt := import("fmt")
req := http.request req := http.request
q := req.url.query q := req.url.query
// List checking. // List checking.
list := [1, 2, 3, 4, 123] list := []
body := req.body rng := int(q.range[0])
if body { fmt.println("range:", q.range)
fmt.println(string(body)) if rng {
pp.print(`<ul name="range">`)
for i:=0 ; i < rng ; i++ {
pp.printf("<li>%d</li>", i)
}
pp.print("</ul>")
} }
}}
{{
if q.name { if q.name {
pp.print("<div id=\"name\">", q.name[0], "</div>") pp.print("<div id=\"name\">", q.name[0], "</div>")
} }
@ -18,7 +26,7 @@
<div> <div>
Hello, Cock! Hello, Cock!
</div> </div>
<div> <div check>
{{ {{
pp.print(req.url.path) pp.print(req.url.path)
}} }}
@ -28,3 +36,7 @@
pp.print("<li>", v, "</li>") pp.print("<li>", v, "</li>")
} }
}}</ul> }}</ul>
<script src="/script.js" ></script>
<div></div>

3
src/request.json Normal file
View file

@ -0,0 +1,3 @@
{
"name":"Andrew"
}

3
src/script.js Normal file
View file

@ -0,0 +1,3 @@
console.log("Hello, World!")

View file

@ -48,10 +48,12 @@ func (pp *Tengo) Eval(
ctx context.Context, ctx context.Context,
recompile bool, recompile bool,
filePath string, filePath string,
preCodes [][]byte,
codes [][]byte, codes [][]byte,
) ([][]byte, error) { ) ([][]byte, error) {
var fullCodeBuf bytes.Buffer var fullCodeBuf bytes.Buffer
const retHead = ` const retHead = `
__context__ := {}
__ret_one__ := bytes("") __ret_one__ := bytes("")
pp := immutable({ pp := immutable({
filepath: __filepath__, filepath: __filepath__,
@ -69,7 +71,6 @@ func (pp *Tengo) Eval(
__ret_one__ += bytes(bts) __ret_one__ += bytes(bts)
} }
}) })
` `
const retSeparator = ` const retSeparator = `
@ -80,6 +81,9 @@ func (pp *Tengo) Eval(
fmt.Fprint(&fullCodeBuf, retHead) fmt.Fprint(&fullCodeBuf, retHead)
for _, preCode := range preCodes {
fmt.Fprintln(&fullCodeBuf, "\n" + string(preCode) + retSeparator)
}
if pp.preCode != nil { if pp.preCode != nil {
fullCodeBuf.Write(pp.preCode(ctx)) fullCodeBuf.Write(pp.preCode(ctx))
} }