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

View file

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

View file

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

21
main.go
View file

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

View file

@ -5,7 +5,11 @@ htmExt := func(c){
c.pp.print(`
<!doctype html>
<html><head>
<title>Check shit</title>
`)
if !is_undefined(c.title) {
c.pp.printf(`<title>%s</title>`, c.title)
}
c.pp.print(`
</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")
req := http.request
q := req.url.query
// List checking.
list := [1, 2, 3, 4, 123]
body := req.body
if body {
fmt.println(string(body))
list := []
rng := int(q.range[0])
fmt.println("range:", q.range)
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 {
pp.print("<div id=\"name\">", q.name[0], "</div>")
}
@ -18,7 +26,7 @@
<div>
Hello, Cock!
</div>
<div>
<div check>
{{
pp.print(req.url.path)
}}
@ -28,3 +36,7 @@
pp.print("<li>", v, "</li>")
}
}}</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,
recompile bool,
filePath string,
preCodes [][]byte,
codes [][]byte,
) ([][]byte, error) {
var fullCodeBuf bytes.Buffer
const retHead = `
__context__ := {}
__ret_one__ := bytes("")
pp := immutable({
filepath: __filepath__,
@ -69,7 +71,6 @@ func (pp *Tengo) Eval(
__ret_one__ += bytes(bts)
}
})
`
const retSeparator = `
@ -80,6 +81,9 @@ func (pp *Tengo) Eval(
fmt.Fprint(&fullCodeBuf, retHead)
for _, preCode := range preCodes {
fmt.Fprintln(&fullCodeBuf, "\n" + string(preCode) + retSeparator)
}
if pp.preCode != nil {
fullCodeBuf.Write(pp.preCode(ctx))
}