github.com/cloudwego/hertz@v0.9.3/examples/html_rendering/main.go (about) 1 /* 2 * Copyright 2022 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "context" 21 "fmt" 22 "html/template" 23 "time" 24 25 "github.com/cloudwego/hertz/pkg/app" 26 "github.com/cloudwego/hertz/pkg/app/server" 27 "github.com/cloudwego/hertz/pkg/common/utils" 28 "github.com/cloudwego/hertz/pkg/protocol/consts" 29 ) 30 31 func formatAsDate(t time.Time) string { 32 year, month, day := t.Date() 33 return fmt.Sprintf("%d/%02d/%02d", year, month, day) 34 } 35 36 func main() { 37 // set interval to 0 means using fs-watching mechanism. 38 h := server.Default(server.WithAutoReloadRender(true, 0)) 39 40 h.Delims("{[{", "}]}") 41 42 h.SetFuncMap(template.FuncMap{ 43 "formatAsDate": formatAsDate, 44 }) 45 h.LoadHTMLGlob("./examples/html_rendering/*") 46 47 h.GET("/index", func(c context.Context, ctx *app.RequestContext) { 48 ctx.HTML(consts.StatusOK, "index.tmpl", utils.H{ 49 "title": "Main website", 50 }) 51 }) 52 53 h.GET("/raw", func(c context.Context, ctx *app.RequestContext) { 54 ctx.HTML(consts.StatusOK, "template.html", utils.H{ 55 "now": time.Date(2017, 0o7, 0o1, 0, 0, 0, 0, time.UTC), 56 }) 57 }) 58 59 h.Spin() 60 }