JSON Response
Learn how to send JSON responses in Iris.
Basic JSON Response
go
package main
import "github.com/kataras/iris/v12"
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
app := iris.New()
app.Get("/json", func(ctx iris.Context) {
user := User{
ID: 1,
Name: "John Doe",
Email: "john@example.com",
}
ctx.JSON(user)
})
app.Listen(":8080")
}
Pretty JSON
go
app.Get("/pretty", func(ctx iris.Context) {
data := iris.Map{
"message": "Hello",
"status": "success",
"data": iris.Map{
"name": "John",
"age": 25,
},
}
ctx.JSON(data, iris.JSON{
Indent: " ",
})
})
Custom JSON Encoding
go
app.Get("/custom", func(ctx iris.Context) {
type CustomTime time.Time
type Event struct {
ID int `json:"id"`
Name string `json:"name"`
Timestamp CustomTime `json:"timestamp"`
}
event := Event{
ID: 1,
Name: "Meeting",
Timestamp: CustomTime(time.Now()),
}
ctx.JSON(event, iris.JSON{
UnescapeHTML: true,
StreamingJSON: true,
})
})
Best Practices
Structure:
- Use proper tags
- Follow conventions
- Document schema
- Handle types
- Validate output
Performance:
- Enable compression
- Use streaming
- Cache responses
- Monitor size
- Handle timeouts
Security:
- Validate input
- Escape output
- Set headers
- Handle errors
- Monitor usage
Maintenance:
- Document schema
- Update structure
- Monitor changes
- Regular testing
- Review security