Skip to content

Commit

Permalink
feat(execute)!: pass template name and writeHeader bool to execute
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Aug 23, 2024
1 parent c9b3ba5 commit 9a45e2e
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 103 deletions.
8 changes: 5 additions & 3 deletions cmd/muxt/testdata/generate/override_execute.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ var formHTML embed.FS

var templates = template.Must(template.ParseFS(formHTML, "*"))

func execute(res http.ResponseWriter, _ *http.Request, t *template.Template, code int, data any) {
func execute(res http.ResponseWriter, _ *http.Request, writeHeader bool, name string, code int, data any) {
fmt.Printf("execute input type %T\n", data)
res.WriteHeader(code)
t.Execute(res, data)
if writeHeader {
res.WriteHeader(code)
}
templates.ExecuteTemplate(res, name, data)
}
-- template_test.go --
package server
Expand Down
19 changes: 10 additions & 9 deletions example/template_routes.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 26 additions & 31 deletions generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ func Generate(templateNames []TemplateName, packageName, templatesVariableName,
}
}
if !hasExecuteFunc {
file.Decls = append(file.Decls, executeFuncDecl())
imports = append(imports, importSpec("bytes"), importSpec("html/template"))
file.Decls = append(file.Decls, executeFuncDecl(templatesVariableName))
imports = append(imports, importSpec("bytes"))
}
for _, imp := range imports {
importGen.Specs = append(importGen.Specs, imp)
Expand Down Expand Up @@ -205,7 +205,7 @@ func (def TemplateName) funcLit(templatesVariableIdent string, method *ast.FuncT
} else {
lit.Body.List = append(lit.Body.List, &ast.AssignStmt{Lhs: []ast.Expr{ast.NewIdent(dataVarIdent)}, Tok: token.DEFINE, Rhs: []ast.Expr{call}})
}
lit.Body.List = append(lit.Body.List, def.executeCall(ast.NewIdent(templatesVariableIdent), httpStatusCode(httpStatusCode200Ident), ast.NewIdent(dataVarIdent)))
lit.Body.List = append(lit.Body.List, def.executeCall(httpStatusCode(httpStatusCode200Ident), ast.NewIdent(dataVarIdent)))
return lit, imports, nil
}

Expand Down Expand Up @@ -365,13 +365,6 @@ func contextContextType() *ast.SelectorExpr {
return &ast.SelectorExpr{X: ast.NewIdent(contextPackageIdent), Sel: ast.NewIdent(contextContextTypeIdent)}
}

func templateTemplateField() *ast.Field {
return &ast.Field{
Names: []*ast.Ident{ast.NewIdent("t")},
Type: &ast.StarExpr{X: &ast.SelectorExpr{X: ast.NewIdent("template"), Sel: ast.NewIdent("Template")}},
}
}

func httpStatusCode(name string) *ast.SelectorExpr {
return &ast.SelectorExpr{
X: ast.NewIdent(httpPackageIdent),
Expand Down Expand Up @@ -837,19 +830,14 @@ func paramParseError(errVar *ast.Ident) *ast.IfStmt {
}
}

func (def TemplateName) executeCall(templatesVariable *ast.Ident, status, data ast.Expr) *ast.ExprStmt {
func (def TemplateName) executeCall(status, data ast.Expr) *ast.ExprStmt {
return &ast.ExprStmt{X: &ast.CallExpr{
Fun: ast.NewIdent(executeIdentName),
Args: []ast.Expr{
ast.NewIdent(TemplateNameScopeIdentifierHTTPResponse),
ast.NewIdent(TemplateNameScopeIdentifierHTTPRequest),
&ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent(templatesVariable.Name),
Sel: ast.NewIdent(templatesLookup),
},
Args: []ast.Expr{&ast.BasicLit{Kind: token.STRING, Value: strconv.Quote(def.name)}},
},
ast.NewIdent("true"),
&ast.BasicLit{Kind: token.STRING, Value: strconv.Quote(def.name)},
status,
data,
},
Expand All @@ -859,7 +847,7 @@ func (def TemplateName) executeCall(templatesVariable *ast.Ident, status, data a
func (def TemplateName) httpRequestReceiverTemplateHandlerFunc(templatesVariableName string) *ast.FuncLit {
return &ast.FuncLit{
Type: httpHandlerFuncType(),
Body: &ast.BlockStmt{List: []ast.Stmt{def.executeCall(ast.NewIdent(templatesVariableName), httpStatusCode(httpStatusCode200Ident), ast.NewIdent(TemplateNameScopeIdentifierHTTPRequest))}},
Body: &ast.BlockStmt{List: []ast.Stmt{def.executeCall(httpStatusCode(httpStatusCode200Ident), ast.NewIdent(TemplateNameScopeIdentifierHTTPRequest))}},
}
}

Expand All @@ -876,15 +864,17 @@ func (def TemplateName) matchReceiver(funcDecl *ast.FuncDecl, receiverTypeIdent
return ok && ident.Name == receiverTypeIdent
}

func executeFuncDecl() *ast.FuncDecl {
func executeFuncDecl(templatesVariableIdent string) *ast.FuncDecl {
const writeHeaderIdent = "writeHeader"
return &ast.FuncDecl{
Name: ast.NewIdent(executeIdentName),
Type: &ast.FuncType{
Params: &ast.FieldList{
List: []*ast.Field{
httpResponseField(),
httpRequestField(),
templateTemplateField(),
{Names: []*ast.Ident{ast.NewIdent(writeHeaderIdent)}, Type: ast.NewIdent("bool")},
{Names: []*ast.Ident{ast.NewIdent("name")}, Type: ast.NewIdent("string")},
{Names: []*ast.Ident{ast.NewIdent("code")}, Type: ast.NewIdent("int")},
{Names: []*ast.Ident{ast.NewIdent(dataVarIdent)}, Type: ast.NewIdent("any")},
},
Expand All @@ -909,10 +899,10 @@ func executeFuncDecl() *ast.FuncDecl {
Tok: token.DEFINE,
Rhs: []ast.Expr{&ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent("t"),
Sel: ast.NewIdent("Execute"),
X: ast.NewIdent(templatesVariableIdent),
Sel: ast.NewIdent("ExecuteTemplate"),
},
Args: []ast.Expr{ast.NewIdent("buf"), ast.NewIdent(dataVarIdent)},
Args: []ast.Expr{ast.NewIdent("buf"), ast.NewIdent("name"), ast.NewIdent(dataVarIdent)},
}},
},
Cond: &ast.BinaryExpr{
Expand Down Expand Up @@ -943,15 +933,20 @@ func executeFuncDecl() *ast.FuncDecl {
},
},
},
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent(httpResponseField().Names[0].Name),
Sel: ast.NewIdent("WriteHeader"),
&ast.IfStmt{
Cond: ast.NewIdent(writeHeaderIdent),
Body: &ast.BlockStmt{List: []ast.Stmt{
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent(httpResponseField().Names[0].Name),
Sel: ast.NewIdent("WriteHeader"),
},
Args: []ast.Expr{ast.NewIdent("code")},
},
},
Args: []ast.Expr{ast.NewIdent("code")},
},
},
}},
&ast.AssignStmt{
Lhs: []ast.Expr{ast.NewIdent("_"), ast.NewIdent("_")},
Tok: token.ASSIGN,
Expand Down
14 changes: 7 additions & 7 deletions generate_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ func TestTemplateName_funcLit(t *testing.T) {
Name: "get",
In: "GET /",
Out: `func(response http.ResponseWriter, request *http.Request) {
execute(response, request, templates.Lookup("GET /"), http.StatusOK, request)
execute(response, request, true, "GET /", http.StatusOK, request)
}`,
},
{
Name: "call F",
In: "GET / F()",
Out: `func(response http.ResponseWriter, request *http.Request) {
data := receiver.F()
execute(response, request, templates.Lookup("GET / F()"), http.StatusOK, data)
execute(response, request, true, "GET / F()", http.StatusOK, data)
}`,
},
{
Expand All @@ -42,7 +42,7 @@ func TestTemplateName_funcLit(t *testing.T) {
},
Out: `func(response http.ResponseWriter, request *http.Request) {
data := receiver.F(request)
execute(response, request, templates.Lookup("GET / F(request)"), http.StatusOK, data)
execute(response, request, true, "GET / F(request)", http.StatusOK, data)
}`,
},
{
Expand All @@ -54,7 +54,7 @@ func TestTemplateName_funcLit(t *testing.T) {
},
Out: `func(response http.ResponseWriter, request *http.Request) {
data := receiver.F(response)
execute(response, request, templates.Lookup("GET / F(response)"), http.StatusOK, data)
execute(response, request, true, "GET / F(response)", http.StatusOK, data)
}`,
},
{
Expand All @@ -67,7 +67,7 @@ func TestTemplateName_funcLit(t *testing.T) {
Out: `func(response http.ResponseWriter, request *http.Request) {
ctx := request.Context()
data := receiver.F(ctx)
execute(response, request, templates.Lookup("GET / F(ctx)"), http.StatusOK, data)
execute(response, request, true, "GET / F(ctx)", http.StatusOK, data)
}`,
},
{
Expand All @@ -80,7 +80,7 @@ func TestTemplateName_funcLit(t *testing.T) {
Out: `func(response http.ResponseWriter, request *http.Request) {
param := request.PathValue("param")
data := receiver.F(param)
execute(response, request, templates.Lookup("GET /{param} F(param)"), http.StatusOK, data)
execute(response, request, true, "GET /{param} F(param)", http.StatusOK, data)
}`,
},
{
Expand All @@ -97,7 +97,7 @@ func TestTemplateName_funcLit(t *testing.T) {
ctx := request.Context()
userName := request.PathValue("userName")
data := receiver.F(ctx, userName)
execute(response, request, templates.Lookup("GET /{userName} F(ctx, userName)"), http.StatusOK, data)
execute(response, request, true, "GET /{userName} F(ctx, userName)", http.StatusOK, data)
}`,
},
} {
Expand Down
Loading

0 comments on commit 9a45e2e

Please sign in to comment.