Using the net/http Package in Go

Welcome to the exciting world of web development in Go! In this chapter, we'll explore the net/http package, which is at the core of building web applications in Go. From understanding the basics to advanced techniques, we'll cover everything you need to know to harness the power of this package and create robust web servers and clients. Let's dive in!

Introduction to the net/http Package

What is the net/http Package?

The net/http package is a part of the standard library in Go and provides essential functionalities for building HTTP servers and clients. It offers an elegant and efficient way to handle HTTP requests and responses, enabling developers to create web applications with ease.

Basic Concepts

  • HTTP Server: A program that listens for incoming HTTP requests and sends back responses.
  • HTTP Client: A program that makes HTTP requests to servers and processes the responses.
  • Handlers: Functions that handle incoming HTTP requests and generate responses.

Building an HTTP Server

Creating a Basic Server

				
					package main

import (
    "fmt"
    "net/http"
)

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

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

				
			
  • http.HandleFunc() registers a handler function for a specific route (“/” in this case).
  • http.ListenAndServe() starts an HTTP server on the specified port (8080) and uses the default router to handle incoming requests.

Handling Different Routes

				
					func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About Page")
}

func contactHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Contact Page")
}

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/about", aboutHandler)
    http.HandleFunc("/contact", contactHandler)
    http.ListenAndServe(":8080", nil)
}

				
			
  • Additional handler functions are registered for specific routes (“/about”, “/contact”).
  • Each handler function responds with different content based on the route.

HTTP Request and Response

Handling HTTP Methods

				
					func handler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        fmt.Fprintf(w, "GET Request")
    } else if r.Method == "POST" {
        fmt.Fprintf(w, "POST Request")
    } else {
        http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
    }
}

				
			
  • Use r.Method to determine the HTTP method of the request.
  • Handle different methods (GET, POST, etc.) appropriately in the handler function.

Reading Request Parameters

				
					func handler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

				
			
  • Use r.URL.Query().Get() to retrieve query parameters from the URL.
  • Process and use the parameters in generating the response.

Middleware

				
					func logger(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

func main() {
    http.Handle("/", logger(http.HandlerFunc(handler)))
    http.ListenAndServe(":8080", nil)
}

				
			

Middleware functions intercept incoming requests and can perform tasks like logging, authentication, etc., before passing them to the main handler.

Routing with Gorilla Mux

				
					import "github.com/gorilla/mux"

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", handler)
    r.HandleFunc("/products/{key}", productHandler)

    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}

				
			
  • Gorilla Mux is a powerful HTTP router package for Go.
  • It allows defining complex routes with parameters and patterns.

In this chapter, we've explored the net/http package in Go and learned how to build powerful HTTP servers and clients. From handling basic requests to implementing advanced features like middleware and routing, you now have the knowledge to create robust and scalable web applications in Go. Keep experimenting, exploring, and building amazing things with Go's net/http package! Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India