Skip to main content

Programming languages · Beginner · 18 min

How to Write and Run Your First Web Server in Go

By Padding · Updated 15 Nov 2026
Go 1.27

You will write a web server in Go 1.27 using only the standard library, with path routes, a JSON endpoint, a POST handler, timeouts and a clean shutdown, then test the handlers without opening a port and build the server into one binary.

On this page

Go's standard library includes a production-grade HTTP server. You do not need a framework to answer requests, route by path and method, read and write JSON, or shut down cleanly. A server written this way compiles to a single file with no dependencies, which is easy to copy to a machine and run.

This tutorial builds a small server one piece at a time: a home page, a route with a parameter, a JSON health check and a POST endpoint that echoes. Then you make it stop cleanly, add a test that checks the handlers without opening a network port, and compile the result into a binary. The handlers live in routes.go and the startup code in main.go, so each step changes only one file.

Step 1 · Create the module

A Go project is a module, which is a folder with a go.mod file naming it. The name usually looks like an import path. It does not have to be a real address when you are not publishing the code:

Bash
mkdir -p ~/hello-web
cd ~/hello-web
go mod init example.com/hello-web
cat go.mod

Check it worked

go mod init prints go: creating new go.mod: module example.com/hello-web. The file holds that module line and a go line with your Go version, such as go 1.27.4. Because the project uses only the standard library, no go.sum file or downloads follow.

Step 2 · Serve a first page

A handler is a function that receives the request and a writer for the response. http.NewServeMux is the router that picks a handler by method and path. Create routes.go with one route:

Bash
cat > routes.go <<'GO'
package main

import (
	"fmt"
	"net/http"
)

func newMux() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", home)
	return mux
}

func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello from Go")
}
GO

The pattern "GET /{$}" matches only the exact path / and only the GET method. Without {$}, a pattern ending in / would match every path below it. Now create main.go, which builds the server and starts it:

Bash
cat > main.go <<'GO'
package main

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

func main() {
	srv := &http.Server{
		Addr:              "127.0.0.1:8080",
		Handler:           newMux(),
		ReadHeaderTimeout: 5 * time.Second,
	}
	log.Println("listening on", srv.Addr)
	log.Fatal(srv.ListenAndServe())
}
GO

The server listens on 127.0.0.1, so only your own machine can reach it. Use ":8080" instead to accept connections from other machines, once you have a firewall in place. ReadHeaderTimeout closes connections from clients that send their request headers too slowly. A server with no timeouts holds each such connection forever, which is an easy way to exhaust it.

Build the program and run it in the background, so you can talk to it from the same terminal. go run . also works, but it starts your program as a separate process that a stop command aimed at go run does not always reach, so this tutorial builds first:

Bash
go build -o hello-web .
./hello-web &

Wait a moment for it to start, then request the page:

Bash
curl -i http://127.0.0.1:8080/

Check it worked

curl -i prints the response headers and body. You should see HTTP/1.1 200 OK, a Content-Type: text/plain; charset=utf-8 header, and the body Hello from Go. In the terminal where you started the server, a line with a time stamp and listening on 127.0.0.1:8080 appears.

Troubleshooting

bind: address already in use means another program already listens on port 8080. Stop it, or change the port in Addr. If curl says Connection refused, the server has not finished compiling and starting; wait a moment and try again. Compile errors print the file name and line number, and the fix is usually a missing import or a typo.

Step 3 · Add routes, JSON and POST

Stop the background server. kill %1 and wait work only in the terminal where you started the server with &. If you started it in the foreground in another terminal, press Ctrl+C there instead. Each time you change the code, stop it, rebuild and start it again:

Bash
kill %1
wait || true

Replace routes.go with a version that adds a path parameter, a JSON response and a JSON request body:

Bash
cat > routes.go <<'GO'
package main

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

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

type echoResponse struct {
	Original string `json:"original"`
	Shouted  string `json:"shouted"`
}

func newMux() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", home)
	mux.HandleFunc("GET /hello/{name}", hello)
	mux.HandleFunc("GET /api/health", health)
	mux.HandleFunc("POST /api/echo", echo)
	return mux
}

func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello from Go")
}

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %s!\n", r.PathValue("name"))
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		log.Println("write response:", err)
	}
}

func health(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}

func echo(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
	var in echoRequest
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "send JSON like {\"message\": \"hi\"}"})
		return
	}
	writeJSON(w, http.StatusOK, echoResponse{
		Original: in.Message,
		Shouted:  strings.ToUpper(in.Message) + "!",
	})
}
GO
gofmt -l .

gofmt -l . lists any file that is not in Go's standard format, so printing nothing means the code is formatted. r.PathValue("name") returns the part of the URL that matched {name}. The struct tags such as json:"message" tell encoding/json which JSON key belongs to each field. http.MaxBytesReader caps the request body at one mebibyte, so a client cannot make the server read an endless upload. Rebuild, start the server again, wait for it to come up, and try each route:

Bash
go build -o hello-web .
./hello-web &
Bash
curl -s http://127.0.0.1:8080/hello/Ada
curl -s http://127.0.0.1:8080/api/health
curl -s -X POST -H 'Content-Type: application/json' -d '{"message":"ship it"}' http://127.0.0.1:8080/api/echo
curl -s -X POST -d 'not json' http://127.0.0.1:8080/api/echo
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8080/
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/nothing-here

Check it worked

The six commands print:

Text
Hello, Ada!
{"status":"ok"}
{"original":"ship it","shouted":"SHIP IT!"}
{"error":"send JSON like {\"message\": \"hi\"}"}
405
404

The 405 means the path exists, but not for the POST method, and the router answers that for you. The 404 is for a path nobody registered.

Step 4 · Shut down cleanly

When the process gets a stop signal, the server above dies at once and cuts any request that is in flight. Handle the signal and give running requests up to ten seconds to finish. Stop the old server, in the same terminal, then replace main.go:

Bash
kill %1
wait || true
cat > main.go <<'GO'
package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	srv := &http.Server{
		Addr:              "127.0.0.1:8080",
		Handler:           newMux(),
		ReadHeaderTimeout: 5 * time.Second,
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	go func() {
		log.Println("listening on", srv.Addr)
		if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done()
	log.Println("shutting down")

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Fatal(err)
	}
	log.Println("stopped")
}
GO
gofmt -l .

signal.NotifyContext cancels a context when the process receives Ctrl+C (os.Interrupt) or SIGTERM, the signal that systemctl stop and docker stop send. The server runs in a goroutine, a lightweight concurrent task, while main waits for the signal. srv.Shutdown stops accepting new connections and waits for active requests to finish, up to the timeout.

Build the program, run it, and stop it with a TERM signal, the same signal a service manager sends:

Bash
go build -o hello-web .
./hello-web &
Bash
curl -s http://127.0.0.1:8080/api/health
kill -TERM %1
wait

Check it worked

The build leaves a file named hello-web in the folder. The curl command prints {"status":"ok"}. After the kill, the server's output ends with shutting down and stopped, each on its own log line, and the shell returns without error. The binary has no dependencies on Go itself. You can copy it to another machine with the same operating system and architecture and run it there.

Step 5 · Test the handlers

Go has testing built in. The net/http/httptest package calls a handler directly with a fake request and records the response, so the test needs no port and no running server:

Bash
cat > routes_test.go <<'GO'
package main

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestHello(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/hello/Grace", nil)
	rec := httptest.NewRecorder()

	newMux().ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}
	if got := rec.Body.String(); got != "Hello, Grace!\n" {
		t.Errorf("body = %q", got)
	}
}

func TestEchoRejectsBadJSON(t *testing.T) {
	req := httptest.NewRequest(http.MethodPost, "/api/echo", strings.NewReader("nope"))
	rec := httptest.NewRecorder()

	newMux().ServeHTTP(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status = %d, want 400", rec.Code)
	}
}

func TestWrongMethod(t *testing.T) {
	req := httptest.NewRequest(http.MethodDelete, "/api/health", nil)
	rec := httptest.NewRecorder()

	newMux().ServeHTTP(rec, req)

	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("status = %d, want 405", rec.Code)
	}
}
GO
go vet ./...
go test -v ./...

go vet looks for suspicious code that compiles but is probably wrong. go test finds every file ending in _test.go and runs each function whose name starts with Test.

Check it worked

go test -v prints === RUN and --- PASS lines for TestHello, TestEchoRejectsBadJSON and TestWrongMethod, then PASS and a line starting ok example.com/hello-web.

Step 6 · Clean up

Remove the project folder. Go itself stays installed:

Bash
cd ~
rm -rf ~/hello-web

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.