Go HTTP Server: Build Your First Web Server

Updated 4 min read
Go HTTP Server featured image: cards showing a handler, a route pattern and middleware

A Go HTTP server can run with just a few lines of code. That is because the standard library already includes a fast, production-ready web server. In this post, you will build one step by step, with routes, path values, status codes and middleware. Each idea comes with code that you can run and test yourself.

Every request runs in its own goroutine, which you learned about in goroutines in Go for beginners. Handlers are also just functions, so a quick look at writing and calling functions in Go helps too.

What Is a Go HTTP Server?

To start, a web server waits for requests from browsers or apps and sends back responses. In addition, HTTP is the set of rules they use to talk. In Go, the net/http package gives you everything you need, with no framework required.

For example, think of a restaurant counter. A customer places an order, the counter sends it to the right cook, and the cook returns a dish. Similarly, a Go HTTP server routes each request to the right function and returns a response.

Your First Go HTTP Server

package main

import (
	"fmt"
	"log"
	"net/http"
)

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /hello", helloHandler)

	fmt.Println("Server running on http://localhost:8080")
	log.Fatal(http.ListenAndServe(":8080", mux))
}

Run it with go run . and open http://localhost:8080/hello in your browser. As a result, you will see “Hello, Go!”. Then ListenAndServe keeps the program running until you press Ctrl+C.

Handlers: w and r

Every handler gets two things. First, r is the request, holding the URL, method, headers and body. Second, w is the response writer, where you write what the user receives.

Routing Requests in a Go HTTP Server

Next, a ServeMux, short for request multiplexer, matches each incoming URL to a handler. The diagram below shows a request travelling through the server.

Go HTTP Server diagram showing a request passing through middleware and ServeMux to a handler

The browser sends a request, middleware logs it, the ServeMux picks a handler, and the handler writes the response.

Methods and Path Values

func userHandler(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	fmt.Fprintf(w, "User ID: %s", id)
}

mux.HandleFunc("GET /users/{id}", userHandler)
// GET /users/42  ->  User ID: 42

Since Go 1.22, a pattern can include the HTTP method and named parts like {id}. Then r.PathValue("id") reads that part. Also, a POST to a GET-only route returns 405 Method Not Allowed for free.

Reading Query Parameters

In addition, query parameters come after the ? in a URL. For example, /hello?name=Smita makes r.URL.Query().Get("name") return “Smita”, so the page says “Hello, Smita!”.

Status Codes and Headers

mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("ok"))
})

Similarly, a status code tells the client how things went, such as 200 OK or 404 Not Found. Set headers first, then the status, and finally write the body. That order matters, because the status and headers go out with the first write.

Middleware: Code That Runs on Every Request

func logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start).Round(time.Millisecond))
	})
}

log.Fatal(http.ListenAndServe(":8080", logging(mux)))
// 2026/10/03 22:32:40 GET /users/42 0s

Middleware wraps a handler with extra work, like logging, login checks or timing. In short, it is a function that takes a handler and returns a new one.

Testing Your Go HTTP Server

curl localhost:8080/hello              # Hello, Go!
curl "localhost:8080/hello?name=Smita" # Hello, Smita!
curl localhost:8080/users/42           # User ID: 42
curl -i -X POST localhost:8080/hello   # HTTP/1.1 405 Method Not Allowed

The curl tool sends requests from your terminal to your Go HTTP server. Add -i to see the status line and headers too.

Common Mistakes with a Go HTTP Server

Error you seeWhy it happensHow to fix it
listen tcp :8080: bind: address already in useAnother program uses port 8080.Stop it or pick another port.
http: superfluous response.WriteHeader callWriteHeader ran after the body was written.Set the status before writing.
Handler keeps running after an errorThe code forgot return after http.Error.Always return right after it.

In particular, the missing return is sneaky, because the user may get two messages glued together. Web server questions also appear in my Go interview questions and answers, so try them next.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • A Go HTTP server needs only the net/http package.
  • Handlers take a ResponseWriter and a Request.
  • ServeMux routes “GET /users/{id}” style patterns, and PathValue reads the parts.
  • Set headers, then status, then write the body.
  • Middleware wraps handlers to add logging or checks.

What’s Next?

Your server can now answer requests. Next, we will combine it with JSON to build a complete REST API.

Coming soon: Go REST API Tutorial for Beginners