HTML Response
Learn how to send HTML responses in Iris.
Basic HTML Response
go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.HTML("<h1>Hello World</h1>")
})
app.Get("/formatted", func(ctx iris.Context) {
name := "John"
ctx.HTML("<h1>Hello %s</h1>", name)
})
app.Listen(":8080")
}
Template Engine
go
func main() {
app := iris.New()
// Register template engine
tmpl := iris.HTML("./views", ".html")
tmpl.Layout("layouts/main.html")
tmpl.Reload(true) // Enable reloading for development
app.RegisterView(tmpl)
app.Get("/", func(ctx iris.Context) {
ctx.ViewData("title", "Home Page")
ctx.ViewData("message", "Welcome!")
ctx.View("index.html")
})
app.Listen(":8080")
}
Partial Views
go
app.Get("/with-partial", func(ctx iris.Context) {
ctx.ViewData("title", "Page with Partial")
ctx.View("page.html")
})
// In page.html:
// {{ partial "header.html" . }}
Best Practices
Security:
- Escape HTML output
- Validate input
- Set security headers
- Prevent XSS
- Handle sensitive data
Performance:
- Cache templates
- Enable compression
- Optimize response size
- Monitor rendering time
- Handle timeouts
Development:
- Use layouts
- Implement partials
- Document structure
- Follow conventions
- Test rendering
Maintenance:
- Regular updates
- Monitor errors
- Clean templates
- Document changes
- Review security