package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"sync"
"github.com/gorilla/mux"
)
// --- Struct Definition (from above) ---
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Photo string `json:"photo"` // Typically a URL or path
}
// --- In-memory storage (from above) ---
var (
users = make(map[int]*User)
usersMutex sync.RWMutex
nextID = 1
)
// --- Handlers ---
// CreateUserHandler handles POST /users
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
var newUser User
// Decode JSON request body into newUser struct
// We don't expect ID in the request body for creation
err := json.NewDecoder(r.Body).Decode(&newUser)
if err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
// Basic validation (optional but recommended)
if newUser.Name == "" {
http.Error(w, "Name is required", http.StatusBadRequest)
return
}
usersMutex.Lock()
// Assign a new ID
newUser.ID = nextID
users[newUser.ID] = &newUser
nextID++
usersMutex.Unlock()
// Respond with the created user and 201 status
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) // 201 Created
json.NewEncoder(w).Encode(newUser)
}
// GetUsersHandler handles GET /users
func GetUsersHandler(w http.ResponseWriter, r *http.Request) {
usersMutex.RLock()
userList := make([]User, 0, len(users))
for _, u := range users {
userList = append(userList, *u) // Dereference pointer to copy value
}
usersMutex.RUnlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userList)
}
// GetUserHandler handles GET /users/{id}
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"] // Get ID from path variable
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid user ID format", http.StatusBadRequest)
return
}
usersMutex.RLock()
user, exists := users[id]
usersMutex.RUnlock()
if !exists {
http.Error(w, "User not found", http.StatusNotFound) // 404 Not Found
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(*user)
}
// UpdateUserHandler handles PUT /users/{id} (Full Update)
func UpdateUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid user ID format", http.StatusBadRequest)
return
}
var updatedUser User
err = json.NewDecoder(r.Body).Decode(&updatedUser)
if err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
// Basic validation (optional but recommended)
if updatedUser.Name == "" {
http.Error(w, "Name is required for PUT", http.StatusBadRequest)
return
}
usersMutex.Lock()
// Check if user exists before updating
if _, exists := users[id]; !exists {
usersMutex.Unlock()
http.Error(w, "User not found", http.StatusNotFound)
return
}
// Replace the entire user object (ensure ID matches)
updatedUser.ID = id // Use the ID from the path
users[id] = &updatedUser
usersMutex.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(updatedUser)
}
// PatchUserHandler handles PATCH /users/{id} (Partial Update)
func PatchUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid user ID format", http.StatusBadRequest)
return
}
// Use a map to decode partial updates
// Allows only specified fields to be present in the JSON body
var patchData map[string]interface{}
err = json.NewDecoder(r.Body).Decode(&patchData)
if err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
usersMutex.Lock()
user, exists := users[id]
if !exists {
usersMutex.Unlock()
http.Error(w, "User not found", http.StatusNotFound)
return
}
// Apply partial updates
if name, ok := patchData["name"]; ok {
if nameStr, ok := name.(string); ok && nameStr != "" { // Check type and non-empty
user.Name = nameStr
} else {
// Decide how to handle invalid type or empty string for name patch
// Option 1: Ignore
// Option 2: Return error
// http.Error(w, "Invalid type or empty value for name", http.StatusBadRequest)
// return
}
}
if photo, ok := patchData["photo"]; ok {
if photoStr, ok := photo.(string); ok { // Check type (allow empty photo string if needed)
user.Photo = photoStr
} else {
// Decide how to handle invalid type for photo patch
}
}
usersMutex.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(*user) // Encode the modified user
}
// --- Main Setup ---
func main() {
router := mux.NewRouter()
// Initialize with some data (optional)
users[1] = &User{ID: 1, Name: "Alice", Photo: "url/to/alice.jpg"}
users[2] = &User{ID: 2, Name: "Bob", Photo: "url/to/bob.jpg"}
nextID = 3
// API Routes
router.HandleFunc("/users", CreateUserHandler).Methods("POST")
router.HandleFunc("/users", GetUsersHandler).Methods("GET")
router.HandleFunc("/users/{id}", GetUserHandler).Methods("GET")
router.HandleFunc("/users/{id}", UpdateUserHandler).Methods("PUT")
router.HandleFunc("/users/{id}", PatchUserHandler).Methods("PATCH")
// Optional: Add DELETE /users/{id} handler here if needed
fmt.Println("Server starting on port 8080...")
log.Fatal(http.ListenAndServe(":8080", router))
}