Skip to main content
In this lesson, you will learn how to send JSON responses using Mizu. JSON is a common format for web apps and APIs to exchange data. Mizu provides a helper method that automatically converts your Go values to JSON and sets the correct headers. You will see how to return structured data from handlers in a clean and simple way.

Code

Create a file named main.go and add this code:
package main

import (
	"log"
	"net/http"
	"time"

	"github.com/go-mizu/mizu"
)

// Welcome handler returning JSON
func welcome(c *mizu.Ctx) error {
	data := map[string]string{
		"message": "Welcome to Mizu JSON API",
	}
	return c.JSON(http.StatusOK, data)
}

// Current time handler
func currentTime(c *mizu.Ctx) error {
	data := map[string]any{
		"time":   time.Now().Format(time.RFC3339),
		"status": "ok",
	}
	return c.JSON(http.StatusOK, data)
}

// User info handler
func userInfo(c *mizu.Ctx) error {
	user := struct {
		Name  string `json:"name"`
		Email string `json:"email"`
	}{
		Name:  "Alice",
		Email: "alice@example.com",
	}
	return c.JSON(http.StatusOK, user)
}

func main() {
	app := mizu.New()

	app.Get("/", welcome)
	app.Get("/time", currentTime)
	app.Get("/user", userInfo)

	if err := app.Listen(":8080"); err != nil {
		log.Fatal(err)
	}
}

Run

Run the server:
go run .
Then open these links in your browser or use curl:

How it works

The c.JSON(statusCode, data) method converts any Go value to JSON, sets the Content-Type: application/json header, and sends the response. You can return maps, slices, or structs. Mizu uses Go’s built-in JSON encoder, and you can use struct tags to define custom field names. If encoding fails, Mizu sends an error response automatically. This makes it easy to build APIs that return structured data without handling JSON manually.

Try something new

Add another route that returns a list of posts:
func listPosts(c *mizu.Ctx) error {
	posts := []map[string]any{
		{"id": 1, "title": "First Post"},
		{"id": 2, "title": "Learning Mizu"},
	}
	return c.JSON(http.StatusOK, posts)
}
Then register it in main():
app.Get("/posts", listPosts)
Visit http://localhost:8080/posts to see the JSON array. Now you can send structured JSON data from any route with just one line of code. Next, continue to Context and Lifecycle to learn how Mizu manages requests, deadlines, and cleanup.