Go > Web Development > HTTP Basics > Handlers and handler functions

Simple HTTP Handler in Go

This snippet demonstrates the creation of a basic HTTP handler function in Go, showcasing how to respond to web requests. It covers the fundamental concepts of creating a handler and registering it to handle specific routes.

Defining a Handler Function

This code defines a handler function named `myHandler` that accepts `http.ResponseWriter` and `*http.Request` as parameters. The `http.ResponseWriter` is used to write the response back to the client, and `*http.Request` contains information about the incoming request. `http.HandleFunc` registers `myHandler` to handle requests to the `/hello` route. Finally, `http.ListenAndServe` starts the HTTP server, listening for incoming connections on port 8080. The second argument is `nil` because we are using the default serve mux.

package main

import (
	"fmt"
	"net/http"
	"log"
)

// Define a handler function
func myHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, World! You requested: %s\n", r.URL.Path)
}

func main() {
	// Register the handler function for a specific route
	http.HandleFunc("/hello", myHandler)

	// Start the HTTP server
	fmt.Println("Server listening on port 8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Concepts Behind the Snippet

HTTP handlers are the core components for building web applications in Go. A handler function takes an `http.ResponseWriter` and an `http.Request` as input, allowing you to process incoming HTTP requests and generate appropriate responses. The `http.HandleFunc` function registers a handler for a specific URL path, enabling your application to route requests to the correct handler based on the requested URL.

Real-Life Use Case

Imagine building a simple API endpoint that returns user data. You could create a handler function that retrieves user information from a database and formats it as JSON, sending it back to the client as the HTTP response. This handler would be registered for a specific route, such as `/users/{userID}`.

Best Practices

Always handle errors properly within your handler functions. Use the `log` package to log errors for debugging and monitoring. Also, consider using middleware to add common functionality like authentication, logging, and request tracing to your handlers. Sanitize and validate input from the request to prevent security vulnerabilities.

Interview Tip

Be prepared to explain the difference between `http.Handler` and `http.HandlerFunc`. `http.Handler` is an interface that requires implementing the `ServeHTTP` method, while `http.HandlerFunc` is an adapter that allows ordinary functions to be used as HTTP handlers. Most commonly, you'll be working with `http.HandlerFunc` for simpler handler definitions.

When to Use Them

Use handler functions whenever you need to process incoming HTTP requests and generate responses. They are the fundamental building blocks of web applications in Go and are used for handling everything from simple static content to complex API endpoints.

Memory Footprint

The memory footprint of a handler function itself is typically small. However, the resources it uses (e.g., database connections, cached data) and the size of the response it generates can impact memory usage. Optimize your handler functions and response sizes to minimize memory consumption.

Alternatives

Alternatives to `http.HandleFunc` include using custom `http.Handler` implementations or using web frameworks like Gin or Echo, which provide more advanced routing and middleware capabilities. These frameworks handle the routing logic behind the scenes.

Pros

Pros of using handler functions include simplicity, flexibility, and direct control over the request handling process. They are easy to understand and implement, making them suitable for small to medium-sized web applications.

Cons

Cons of using only handler functions and the standard library for large applications include the lack of built-in support for advanced features like routing, middleware, and templating. You might need to implement these features yourself, which can be time-consuming.

FAQ

  • What is the difference between http.Handler and http.HandlerFunc?

    http.Handler is an interface that requires implementing the ServeHTTP method. http.HandlerFunc is an adapter that allows ordinary functions to be used as HTTP handlers. It implements the http.Handler interface by calling the function.
  • How do I handle different HTTP methods (GET, POST, PUT, DELETE) in my handler function?

    You can inspect the r.Method field of the http.Request object to determine the HTTP method and execute different logic accordingly. Use conditional statements (if or switch) to branch based on the method.