~/Go HTTP Server Implementation from Scratch

Jan 15, 2019


To build a basic HTTP server from scratch in Go, use the standard library net/http. This package lets you quickly set up a server, handle routes, and serve responses.

Minimal Go HTTP server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
  "fmt"
  "net/http"
)

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

func main() {
  http.HandleFunc("/", handler)
  err := http.ListenAndServe(":8080", nil)
  if err != nil {
    panic(err)
  }
}

How it works:

Run the program, then navigate to http://localhost:8080/ to see the response.

For production, consider using context, logging, and graceful shutdown techniques. See the Go documentation for advanced usage.

Tags: [golang] [http] [server]