Skip to content
Hierarchy
http-server-go.mdx

Creating a Basic HTTP Server with Go

A guide to building a simple HTTP server in Go with practical examples.

By Ahsan Azizan · · 3 min read

In this post we build an HTTP server in Go that answers GET / with a greeting, then extend it into a small JSON API for users. Go's standard library covers all of it, so there is nothing to install beyond Go itself.

Prerequisites

Install Go from the Go website.

Set up the project

mkdir go-http-server
cd go-http-server

Create a file named main.go for the server code.

// main.go

package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Your HTTP server code will go here
}

Handle an HTTP request

Requests are handled through the net/http package. Write a handler function that responds to incoming requests.

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
)

func get(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("Responding to GET / /\n")
	io.WriteString(w, "Hello World!\n")
}

Register the handler and start the server. http.ListenAndServe blocks until the server stops, so check the error it returns.

func main() {
	http.HandleFunc("/", get)

	err := http.ListenAndServe(":8080", nil)
	if errors.Is(err, http.ErrServerClosed) {
		fmt.Printf("Server closed\n")
	} else if err != nil {
		fmt.Printf("Error starting server: %s\n", err)
		os.Exit(1)
	}
}

Run the server

Save main.go and run it.

go run main.go

Open http://localhost:8080 in a browser. You see the message Hello World!.

curl gives you the same response.

curl http://localhost:8080/

That is a working HTTP server.

Route by method with ServeMux

One handler on / only gets you so far. http.NewServeMux lets you route requests yourself, so the same path can answer GET and POST differently. The example below keeps users in a map and returns JSON.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"net/http"
	"os"
)

type User struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

var users map[string]User
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func generateId(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}

	return string(b)
}

func getUsers(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("Responding to GET /\n")

	usersList := make([]User, 0, len(users))

	for _, user := range users {
		usersList = append(usersList, user)
	}

	res, err := json.Marshal(usersList)
	if err != nil {
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(res)
}

func createUser(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("Responding to POST /\n")

	var newUser User
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&newUser)

	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	newUser.ID = generateId(12)
	users[newUser.ID] = newUser

	res, err := json.Marshal(newUser)
	if err != nil {
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(res)
}

func main() {
	users = make(map[string]User)

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			getUsers(w, r)
		case http.MethodPost:
			createUser(w, r)
		}
	})

	err := http.ListenAndServe(":8080", mux)

	if errors.Is(err, http.ErrServerClosed) {
		fmt.Printf("Server closed")
	} else if err != nil {
		fmt.Printf("Error starting server: %s\n", err)
		os.Exit(1)
	}
}

What struck me most while writing this is how little you need. Serving requests, decoding JSON, and routing by method all come out of net/http, with no framework in the way. That is a fair reason to reach for Go on a small service, and it is where I plan to keep digging.