Skip to content

Instantly share code, notes, and snippets.

@codemartial
Created August 5, 2026 02:15
Show Gist options
  • Select an option

  • Save codemartial/25fc9edbe1b0e45755cbbfbb95ba954b to your computer and use it in GitHub Desktop.

Select an option

Save codemartial/25fc9edbe1b0e45755cbbfbb95ba954b to your computer and use it in GitHub Desktop.
A buggy multi-process hello world.
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"sync"
)
const userFile = "users.txt"
type UserRegistry struct {
mu sync.Mutex
users map[string]bool
}
func loadUsers(path string) map[string]bool {
users := make(map[string]bool)
f, err := os.Open(path)
if err != nil {
return users // no file yet, start fresh
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
users[scanner.Text()] = true
}
return users
}
func (r *UserRegistry) sayHello(toWhom string) string {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.users[toWhom]; ok {
return "Hello registered user " + toWhom
}
r.users[toWhom] = true
f, err := os.OpenFile(userFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return "Hello new user " + toWhom + " (failed to persist: " + err.Error() + ")"
}
defer f.Close()
fmt.Fprintln(f, toWhom)
return "Hello new user " + toWhom
}
func main() {
registry := &UserRegistry{users: loadUsers(userFile)}
http.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
toWhom := req.URL.Query().Get("name")
if toWhom == "" {
http.Error(w, "missing name parameter", http.StatusBadRequest)
return
}
fmt.Fprintln(w, registry.sayHello(toWhom))
})
fmt.Println("Listening on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println("Server error:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment