Introduction

Go’s net/http package provides a powerful yet simple HTTP server implementation. This article demonstrates how to start a working HTTP server with minimal code.

Minimal Implementation

package main

import (
    "fmt"
    "net/http"
)

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

    fmt.Println("Server started at :8080")
    http.ListenAndServe(":8080", nil)
}

Code Breakdown

Route Registration

http.HandleFunc("/", handler)

HandleFunc maps a URL path to a handler function. The first parameter is the path pattern, and the second is a function of type func(ResponseWriter, *Request).

Starting the Server

http.ListenAndServe(":8080", nil)
  • First parameter: listen address (:8080 means listen on port 8080 on all interfaces)
  • Second parameter: custom Handler (passing nil uses DefaultServeMux)

Extended Version with Multiple Routes

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type Response struct {
    Message string `json:"message"`
}

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

func apiHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(Response{Message: "API response"})
}

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/api", apiHandler)

    fmt.Println("Server running at http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

Key Takeaways

  1. Simplicity: A Go HTTP server can be started with less than 10 lines of code
  2. Standard Library: Production-ready servers can be built without third-party frameworks
  3. Concurrent Handling: Each request is handled in a separate goroutine

Further Reading

Summary

Go’s net/http package offers a clean and powerful API for building HTTP services. Understanding the basics allows you to choose whether to introduce frameworks (like Gin or Echo) based on your needs.