Skip to content

Instantly share code, notes, and snippets.

@philwinder
Created June 12, 2025 08:09
Show Gist options
  • Select an option

  • Save philwinder/db2e17413332844fa4b14971ae5adb34 to your computer and use it in GitHub Desktop.

Select an option

Save philwinder/db2e17413332844fa4b14971ae5adb34 to your computer and use it in GitHub Desktop.
A mock "users" microservice in Go (Toy example)
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
)
// User represents a user entity
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// UserService encapsulates business logic for users
type UserService struct {
users []User
}
// NewUserService creates a new UserService with mock data
func NewUserService() *UserService {
return &UserService{
users: []User{
{ID: 1, Name: "alice", Email: "alice@example.com"},
{ID: 2, Name: "bob", Email: "bob@example.com"},
{ID: 3, Name: "carol", Email: "carol@example.com"},
},
}
}
// GetUsersWithCapitalizedNames applies business logic to user data
func (s *UserService) GetUsersWithCapitalizedNames() []User {
result := make([]User, len(s.users))
for i, u := range s.users {
u.Name = strings.Title(u.Name)
result[i] = u
}
return result
}
// UserHandler encapsulates the HTTP layer
type UserHandler struct {
service *UserService
}
// NewUserHandler creates a new UserHandler
func NewUserHandler(service *UserService) *UserHandler {
return &UserHandler{service: service}
}
// ServeHTTP implements http.Handler for UserHandler
func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
userList := h.service.GetUsersWithCapitalizedNames()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userList)
}
func main() {
userService := NewUserService()
userHandler := NewUserHandler(userService)
http.Handle("/users", userHandler)
log.Println("Starting server on :8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment