-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmain.go
More file actions
407 lines (348 loc) · 12 KB
/
Copy pathmain.go
File metadata and controls
407 lines (348 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package main
import (
"net/http"
"sort"
"strconv"
"strings"
server "github.com/ckanthony/gin-mcp"
"github.com/gin-gonic/gin"
)
// Product represents a product in our store
type Product struct {
ID int `json:"id" jsonschema:"readOnly"`
Name string `json:"name" jsonschema:"required,description=Name of the product"`
Description string `json:"description,omitempty" jsonschema:"description=Detailed description of the product"`
Price float64 `json:"price" jsonschema:"required,minimum=0,description=Price in USD"`
Tags []string `json:"tags,omitempty" jsonschema:"description=Categories or labels for the product"`
IsEnabled bool `json:"is_enabled" jsonschema:"required,description=Whether the product is available for purchase"`
}
// UpdateProductRequest represents the request body for updating a product
type UpdateProductRequest struct {
Name string `json:"name" jsonschema:"required,description=New name of the product"`
Description string `json:"description,omitempty" jsonschema:"description=New description of the product"`
Price float64 `json:"price" jsonschema:"required,minimum=0,description=New price in USD"`
Tags []string `json:"tags,omitempty" jsonschema:"description=New categories or labels"`
IsEnabled bool `json:"is_enabled" jsonschema:"required,description=New availability status"`
}
// ListProductsParams defines query parameters for product listing and searching
type ListProductsParams struct {
// Search parameters
Query string `form:"q" json:"q,omitempty" jsonschema:"description=Search query string for product name and description"`
// Filter parameters
MinPrice float64 `form:"minPrice" json:"minPrice,omitempty" jsonschema:"description=Minimum price filter"`
MaxPrice float64 `form:"maxPrice" json:"maxPrice,omitempty" jsonschema:"description=Maximum price filter"`
Tag string `form:"tag" json:"tag,omitempty" jsonschema:"description=Filter by specific tag"`
Enabled *bool `form:"enabled" json:"enabled,omitempty" jsonschema:"description=Filter by availability status"`
// Pagination parameters
Page int `form:"page,default=1" json:"page,omitempty" jsonschema:"description=Page number,minimum=1,default=1"`
Limit int `form:"limit,default=10" json:"limit,omitempty" jsonschema:"description=Items per page,minimum=1,maximum=100,default=10"`
// Sorting parameters
SortBy string `form:"sortBy,default=id" json:"sortBy,omitempty" jsonschema:"description=Field to sort by,enum=id,enum=price"`
Order string `form:"order,default=asc" json:"order,omitempty" jsonschema:"description=Sort order,enum=asc,enum=desc"`
}
// In-memory store
var (
products = make(map[int]*Product)
nextID = 1
)
// Initialize sample products
func init() {
products[nextID] = &Product{
ID: nextID,
Name: "Quantum Bug Repellent",
Description: "Keeps bugs out of your code using quantum entanglement. Warning: May cause Schrödinger's bugs",
Price: 15.99,
Tags: []string{"programming", "quantum", "debugging"},
IsEnabled: true,
}
nextID++
products[nextID] = &Product{
ID: nextID,
Name: "HTTP Status Cat Poster",
Description: "A poster featuring cats representing HTTP status codes. 404 Cat Not Found included!",
Price: 19.99,
Tags: []string{"web", "cats", "decoration"},
IsEnabled: true,
}
nextID++
products[nextID] = &Product{
ID: nextID,
Name: "Rubber Duck Debug Force™",
Description: "Special forces rubber duck trained in advanced debugging techniques. Has PhD in Computer Science",
Price: 42.42,
Tags: []string{"debugging", "rubber-duck", "consultant"},
IsEnabled: true,
}
nextID++
products[nextID] = &Product{
ID: nextID,
Name: "Infinite Loop Coffee Maker",
Description: "Keeps making coffee until stack overflow. Comes with catch{} block cup holder",
Price: 99.99,
Tags: []string{"coffee", "programming", "kitchen"},
IsEnabled: true,
}
nextID++
}
func main() {
gin.SetMode(gin.DebugMode)
// Use Default() which includes logger and recovery middleware
r := gin.Default()
// Register API routes
registerRoutes(r)
// Initialize and configure MCP server
configureMCP(r)
// Start the server
r.Run(":8080")
}
// Register API routes
func registerRoutes(r *gin.Engine) {
// CRUD endpoints
r.GET("/products", listProducts)
r.GET("/products/:id", getProduct)
r.POST("/products", createProduct)
r.PUT("/products/:id", updateProduct)
r.DELETE("/products/:id", deleteProduct)
// Search endpoint
r.GET("/products/search", searchProducts)
}
// Configure MCP server
func configureMCP(r *gin.Engine) {
mcp := server.New(r, &server.Config{
Name: "Gaming Store API",
Description: "RESTful API for managing gaming products",
BaseURL: "http://localhost:8080",
})
// Register request schemas for MCP
mcp.RegisterSchema("GET", "/products", ListProductsParams{}, nil)
mcp.RegisterSchema("POST", "/products", nil, Product{})
mcp.RegisterSchema("PUT", "/products/:id", nil, UpdateProductRequest{})
// Mount MCP endpoint
mcp.Mount("/mcp")
}
// Handler functions
// listProducts retrieves a paginated list of products with filtering and sorting
// @summary List all products
// @description Returns a paginated list of products with optional filtering by price, tags, and availability. Supports sorting and full-text search.
// @param page Page number for pagination (default: 1, minimum: 1)
// @param limit Number of items per page (default: 10, max: 100)
// @param minPrice Minimum price filter in USD
// @param maxPrice Maximum price filter in USD
// @param tag Filter products by a specific tag
// @param enabled Filter by availability status (true/false)
// @param sortBy Field to sort by (id or price, default: id)
// @param order Sort order (asc or desc, default: asc)
// @tags public catalog products
func listProducts(c *gin.Context) {
var params ListProductsParams
if err := c.ShouldBindQuery(¶ms); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate and normalize pagination params
params.Page = max(params.Page, 1)
params.Limit = clamp(params.Limit, 1, 100)
var result []*Product
// Apply filters
for _, product := range products {
if !applyFilters(product, ¶ms) {
continue
}
result = append(result, product)
}
// Sort results
sortProducts(&result, params.SortBy, params.Order)
// Apply pagination
paginatedResult := paginateResults(result, params.Page, params.Limit)
// Return response with metadata
c.JSON(http.StatusOK, gin.H{
"products": paginatedResult,
"meta": gin.H{
"page": params.Page,
"limit": params.Limit,
"total": len(result),
"totalPages": (len(result) + params.Limit - 1) / params.Limit,
},
})
}
// searchProducts performs full-text search across products
// @summary Search products
// @description Searches for products by name and description using a full-text query
// @param q Search query string (required) - searches product names and descriptions
// @tags public catalog products search
func searchProducts(c *gin.Context) {
query := strings.ToLower(c.Query("q"))
if query == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Search query is required"})
return
}
var results []*Product
for _, product := range products {
if matchesSearchQuery(product, query) {
results = append(results, product)
}
}
c.JSON(http.StatusOK, gin.H{
"products": results,
"meta": gin.H{
"total": len(results),
"query": query,
},
})
}
// getProduct retrieves a single product by its ID
// @summary Get product details
// @description Returns detailed information for a specific product including name, description, price, tags, and availability
// @param id The unique product identifier
// @tags public catalog products
func getProduct(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if product, exists := products[id]; exists {
c.JSON(http.StatusOK, product)
return
}
c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
}
// createProduct adds a new product to the catalog
// @summary Create new product
// @description Creates a new product with the provided details and returns the created product with its assigned ID
// @param name Product name (required)
// @param description Detailed description of the product
// @param price Product price in USD (required, must be >= 0)
// @param tags Categories or labels for the product
// @param is_enabled Whether the product is available for purchase (required)
// @tags admin products write
func createProduct(c *gin.Context) {
var product Product
if err := c.ShouldBindJSON(&product); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
product.ID = nextID
nextID++
products[product.ID] = &product
c.JSON(http.StatusCreated, product)
}
// updateProduct modifies an existing product
// @summary Update product
// @description Updates all fields of an existing product and returns the updated product data
// @param id The unique product identifier (path parameter)
// @param name New product name (required)
// @param description New detailed description
// @param price New price in USD (required, must be >= 0)
// @param tags New categories or labels
// @param is_enabled New availability status (required)
// @tags admin products write
func updateProduct(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if _, exists := products[id]; exists {
var updateReq UpdateProductRequest
if err := c.ShouldBindJSON(&updateReq); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
updatedProduct := &Product{
ID: id,
Name: updateReq.Name,
Description: updateReq.Description,
Price: updateReq.Price,
Tags: updateReq.Tags,
IsEnabled: updateReq.IsEnabled,
}
products[id] = updatedProduct
c.JSON(http.StatusOK, updatedProduct)
return
}
c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
}
// deleteProduct removes a product from the catalog
// @summary Delete product
// @description Permanently removes a product from the catalog by its ID
// @param id The unique product identifier
// @tags admin products write
func deleteProduct(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if _, exists := products[id]; exists {
delete(products, id)
c.Status(http.StatusNoContent)
return
}
c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
}
// Helper functions
func applyFilters(product *Product, params *ListProductsParams) bool {
// Price filter
if params.MinPrice > 0 && product.Price < params.MinPrice {
return false
}
if params.MaxPrice > 0 && product.Price > params.MaxPrice {
return false
}
// Tag filter
if params.Tag != "" && !containsTag(product.Tags, params.Tag) {
return false
}
// Enabled filter
if params.Enabled != nil && product.IsEnabled != *params.Enabled {
return false
}
return true
}
func containsTag(tags []string, tag string) bool {
for _, t := range tags {
if t == tag {
return true
}
}
return false
}
func matchesSearchQuery(product *Product, query string) bool {
return strings.Contains(strings.ToLower(product.Name), query) ||
strings.Contains(strings.ToLower(product.Description), query)
}
func sortProducts(products *[]*Product, sortBy, order string) {
sortBy = strings.ToLower(sortBy)
order = strings.ToLower(order)
sort.Slice(*products, func(i, j int) bool {
a := (*products)[i]
b := (*products)[j]
var comparison bool
switch sortBy {
case "price":
comparison = a.Price < b.Price
default:
comparison = a.ID < b.ID
}
return comparison != (order == "desc")
})
}
func paginateResults(results []*Product, page, limit int) []*Product {
start := (page - 1) * limit
if start >= len(results) {
return []*Product{}
}
end := min(start+limit, len(results))
return results[start:end]
}
// Utility functions
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func clamp(value, min, max int) int {
if value < min {
return min
}
if value > max {
return max
}
return value
}