Sling Academy
Home/Golang/Routing with `net/http`: Basics of Go Web Servers

Routing with `net/http`: Basics of Go Web Servers

Last updated: November 27, 2024

In Go, one of the foundational packages for creating web servers is net/http. This package allows you to build simple web servers that can handle basic HTTP requests. This article explores some basic concepts of routing using the net/http package, providing easy-to-follow examples to help you get started with Go web servers.

Setting Up a Simple Web Server

Before diving into routing, let's set up a basic web server. Here's a minimal example that listens for incoming HTTP requests and responds with "Hello, World!".


package main

import (
    "fmt"
    "net/http"
)

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

func main() {
    http.HandleFunc("/", helloWorld)
    http.ListenAndServe(":8080", nil)
}

The web server listens on port 8080 and responds to any request to / with the text "Hello, World!". The key function here is http.HandleFunc, which associates a request path with a handler function.

Understanding Handlers and Routes

In Go's net/http package, a handler is essentially a function that implements the http.Handler interface, allowing it to respond to specific HTTP requests.

The HandleFunc convenience method is frequently used to map functions directly to request paths, creating the basic construct we refer to as a "route".

Creating Multiple Routes

To create multiple routes, simply add additional calls to http.HandleFunc, each with its unique path and handler function:


func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to the Home Page!")
}

func aboutPage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "This is the About Page.")
}

func main() {
    http.HandleFunc("/", homePage)
    http.HandleFunc("/about", aboutPage)
    http.ListenAndServe(":8080", nil)
}

In the example above, requests to / will trigger homePage, while requests to /about will trigger aboutPage.

Using an HTTP Router

While the vanilla net/http package allows routing, often you'd need more powerful routing capabilities. That's where third-party HTTP routers come in. For more complex URL patterns, you might consider using an external router like gorilla/mux.

First, you'll need to install gorilla/mux:


go get -u github.com/gorilla/mux

Here's an example using gorilla/mux to setup routes:


package main

import (
    "fmt"
    "net/http"
    "github.com/gorilla/mux"
)

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to the Home Page!")
}

func aboutPage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to the About Page!")
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", homePage)
    r.HandleFunc("/about", aboutPage)
    http.ListenAndServe(":8080", r)
}

With gorilla/mux, you can easily handle more advanced routing scenarios such as route variables, regex, and more.

Conclusion

Understanding the routing basics of the net/http package in Go is fundamental to building web applications. You’ve now seen how to handle simple routing and how to extend routing capabilities with gorilla/mux. These foundational skills should help you build simple web servers and services using Go.

Next Article: Using Middleware to Extend Go HTTP Servers

Previous Article: Handling JSON Requests and Responses in Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant