Sharing state between net/http method calls in Go

Featured image for sharing metadata for article

I've recently been writing some HTTP server code with Go, and found it not-super-searchable to find out how to have a struct that shares state between method calls, so I thought it'd be good to blogument it.

For a super contrived example, we want to share the state along our server type, which requires we have our HTTP handler functions defined on the struct, and we set up the HandleFuncs on the instance of the struct:

package main

import (
	"log"
	"net/http"
)

type server struct {
	state string // not handled atomically, as it should be in production code
}

func (s server) handleFunc(w http.ResponseWriter, _ *http.Request) {
	w.Write([]byte(s.state))
}

func main() {
	mux := http.NewServeMux()

	server := server{
		state: "this is shared",
	}

	mux.HandleFunc("/", server.handleFunc)

	s := http.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	log.Fatal(s.ListenAndServe())
}

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.