0
0
GoHow-ToBeginner · 3 min read

How to Use http.HandleFunc in Go for Simple HTTP Servers

In Go, use http.HandleFunc to register a function that handles HTTP requests for a specific path. This function takes a URL pattern and a handler function with signature func(http.ResponseWriter, *http.Request). Then start the server with http.ListenAndServe to listen for incoming requests.
📐

Syntax

The http.HandleFunc function registers a handler function for a given URL pattern. It has two parameters:

  • pattern: a string representing the URL path to match (e.g., "/hello")
  • handler: a function with signature func(http.ResponseWriter, *http.Request) that processes the request and writes the response

After registering handlers, you start the server with http.ListenAndServe, specifying the address and nil to use the default handler.

go
http.HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
💻

Example

This example shows how to create a simple HTTP server that responds with "Hello, World!" when you visit http://localhost:8080/hello.

go
package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, World!")
}

func main() {
	http.HandleFunc("/hello", helloHandler)
	fmt.Println("Server starting at http://localhost:8080/hello")
	http.ListenAndServe(":8080", nil)
}
Output
Server starting at http://localhost:8080/hello
⚠️

Common Pitfalls

Some common mistakes when using http.HandleFunc include:

  • Not matching the URL path exactly, causing 404 errors.
  • Forgetting to call http.ListenAndServe to start the server.
  • Using a handler function with the wrong signature.
  • Not writing any response, which leaves the client hanging.

Here is an example of a wrong handler and the correct way:

go
package main

import (
	"fmt"
	"net/http"
)

// Wrong: handler missing parameters
// func wrongHandler() {
//     fmt.Println("This won't work")
// }

// Correct handler signature
func correctHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "This works!")
}

func main() {
	// http.HandleFunc("/wrong", wrongHandler) // This will cause a compile error
	http.HandleFunc("/correct", correctHandler)
	http.ListenAndServe(":8080", nil)
}
📊

Quick Reference

Remember these key points when using http.HandleFunc:

  • Use exact URL paths for routing.
  • Handler functions must have the signature func(http.ResponseWriter, *http.Request).
  • Call http.ListenAndServe to start the server.
  • Write a response to http.ResponseWriter to avoid empty replies.

Key Takeaways

Use http.HandleFunc to link URL paths to handler functions with the correct signature.
Always start the server with http.ListenAndServe after registering handlers.
Write responses inside your handler to communicate with clients.
Match URL patterns exactly to avoid 404 errors.
Handler functions must accept http.ResponseWriter and *http.Request parameters.