A Complete Guide - GoLang Web Programming Building HTTP Servers with net http

Last Updated: 03 Jul, 2025   
  YOU NEED ANY HELP? THEN SELECT ANY TEXT.

Explaining GoLang Web Programming: Building HTTP Servers with net/http

1. Basics of HTTP Server Setup

Creating an HTTP server in Go is straightforward. Here’s a minimal example:

package main

import (
    "fmt"
    "net/http"
)

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

func main() {
    http.HandleFunc("/hello", helloWorldHandler)
    fmt.Println("Starting server at port 8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}
  • http.HandleFunc: This function registers a handler function for a specified path. In the example, helloWorldHandler is registered for the path /hello.
  • http.ListenAndServe: This function starts an HTTP server on the specified port and network address. The second argument is a Handler; if nil, the DefaultServeMux is used.

2. Handling Requests

The handler function (helloWorldHandler) is where the real work happens. It takes two parameters:

  • http.ResponseWriter: Used to write HTTP response headers and data.
  • http.Request: Holds all information about the HTTP request.

Example: Handling different HTTP methods

func handleGET(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, "Unsupported method", http.StatusMethodNotAllowed)
        return
    }
    fmt.Fprintf(w, "GET request received")
}

3. Routing

While http.HandleFunc works well for small applications, routing libraries like gorilla/mux or chi provide more advanced capabilities.

Example with gorilla/mux

package main

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

func helloHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    name := vars["name"]
    fmt.Fprintf(w, "Hello, %s!", name)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/hello/{name}", helloHandler).Methods("GET")
    http.Handle("/", r)
    fmt.Println("Starting server at port 8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}
  • mux.Vars: Extracts variables from URL path.

4. Middleware

Middleware functions allow you to run code before or after handling HTTP requests.

Example of Middleware

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        next.ServeHTTP(w, r)
        duration := time.Since(start)
        fmt.Printf("Request to %s took %s\n", r.URL.Path, duration)
    })
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/hello", helloWorldHandler).Methods("GET")
    loggedRouter := loggingMiddleware(r)
    http.Handle("/", loggedRouter)
    fmt.Println("Starting server at port 8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

5. Serving Static Files

Handling static files (CSS, JavaScript, images) can be done easily using http.FileServer.

Example of Serving Static Files

func main() {
    fs := http.FileServer(http.Dir("static/"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.HandleFunc("/hello", helloWorldHandler)
    fmt.Println("Starting server at port 8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

6. Error Handling

Proper error handling is crucial for maintaining robust applications. Use http.Error to send error messages.

Example of Error Handling

func helloHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    name, ok := vars["name"]
    if !ok {
        http.Error(w, "Name parameter required", http.StatusBadRequest)
        return
    }
    fmt.Fprintf(w, "Hello, %s!", name)
}

7. HTTPS Support

For secure communication, serve your application over HTTPS.

Example of HTTPS Server

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement GoLang Web Programming Building HTTP Servers with net http

Introduction

Go has a built-in net/http package that makes it easy to write HTTP servers and clients. In this guide, we'll walk you through creating a simple HTTP server that handles requests and responds with a message.

Prerequisites

Make sure you have the following installed on your system:

Login to post a comment.