Created
June 12, 2025 08:12
-
-
Save philwinder/7aa38185e20433c04c533f2b28f4e217 to your computer and use it in GitHub Desktop.
A mock "orders" microservice in Go (Toy Example)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
// Order represents an order entity | |
type Order struct { | |
ID int `json:"id"` | |
UserID int `json:"user_id"` | |
Amount float64 `json:"amount"` | |
Status string `json:"status"` | |
} | |
// OrderService encapsulates business logic for orders | |
type OrderService struct { | |
orders []Order | |
} | |
// NewOrderService creates a new OrderService with mock data | |
func NewOrderService() *OrderService { | |
return &OrderService{ | |
orders: []Order{ | |
{ID: 1, UserID: 1, Amount: 99.99, Status: "pending"}, | |
{ID: 2, UserID: 2, Amount: 49.50, Status: "shipped"}, | |
{ID: 3, UserID: 1, Amount: 15.00, Status: "delivered"}, | |
}, | |
} | |
} | |
// GetOrdersByUser returns all orders for a given user | |
func (s *OrderService) GetOrdersByUser(userID int) []Order { | |
var result []Order | |
for _, o := range s.orders { | |
if o.UserID == userID { | |
result = append(result, o) | |
} | |
} | |
return result | |
} | |
// GetAllOrders returns all orders | |
func (s *OrderService) GetAllOrders() []Order { | |
return s.orders | |
} | |
// OrderHandler encapsulates the HTTP layer | |
type OrderHandler struct { | |
service *OrderService | |
} | |
// NewOrderHandler creates a new OrderHandler | |
func NewOrderHandler(service *OrderService) *OrderHandler { | |
return &OrderHandler{service: service} | |
} | |
// ServeHTTP implements http.Handler for OrderHandler | |
func (h *OrderHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
if r.Method == http.MethodGet { | |
// Optionally filter by user_id query param | |
userIDs, ok := r.URL.Query()["user_id"] | |
if ok && len(userIDs) > 0 { | |
// For simplicity, ignore error handling for Atoi | |
userID := 0 | |
fmt.Sscanf(userIDs[0], "%d", &userID) | |
orders := h.service.GetOrdersByUser(userID) | |
json.NewEncoder(w).Encode(orders) | |
return | |
} | |
orders := h.service.GetAllOrders() | |
json.NewEncoder(w).Encode(orders) | |
return | |
} | |
w.WriteHeader(http.StatusMethodNotAllowed) | |
} | |
func main() { | |
orderService := NewOrderService() | |
orderHandler := NewOrderHandler(orderService) | |
http.Handle("/orders", orderHandler) | |
log.Println("Orders service running on :8081...") | |
log.Fatal(http.ListenAndServe(":8081", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment