Autostrada
Autostrada
Create a new codebase Get Autostrada Plus
Documentation Changelog Roadmap Give feedback
Login

DocumentationJSON API › Creating handlers

Creating handlers

Handlers are responsible for executing your business logic and writing HTTP responses.

Your generated codebase will already contain some handlers in the cmd/api/handlers.go file. The exact contents of this file will vary depending on the options you select, but in all cases you'll see a home handler which looks similar to this:

func (app *application) status(w http.ResponseWriter, r *http.Request) {
	data := map[string]string{
		"Status": "OK",
	}

	err := response.JSON(w, http.StatusOK, data)
	if err != nil {
		app.serverError(w, r, err)
	}
}

You can follow this pattern to create your own handlers. Specifically, handlers should be defined as http.HandlerFunc methods on the application struct, using the following pattern:

func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
    // Your handler logic...
}

For small applications, it's fine for all handlers to live in the cmd/api/handlers.go file. As your application grows, you may wish to split them across multiple files – for example, handlers_auth.go, handlers_admin.go, and so on.