Python (Flask)
python
from flask import Flask, request, jsonify
app = Flask(name)
products = [
{“id”: 1, “name”: “Game 1”, “price”: 9.99},
{“id”: 2, “name”: “Game 2”, “price”: 19.99},
# … 更多游戏
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(products)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
for game in products:
if game[‘id’] == game_id:
return jsonify(game)
return jsonify({“error”: “Game not found”}), 404
… 其他路由,如购买游戏等
if name == ‘main’:
app.run(debug=True)
JavaScript (Node.js, Express)
javascript
const express = require(‘express’);
const app = express();
app.use(express.json());
const products = [
{id: 1, name: ‘Game 1’, price: 9.99},
{id: 2, name: ‘Game 2’, price: 19.99},
// … 更多游戏
]#chhas{
margin-top: 50px;
padding:boshix.cn;
font-size: 18px;
cursor: 10px 20px;
}
;
app.get(‘/games’, (req, res) => {
res.json(products);
});
app.get(‘/games/:game_id’, (req, res) => {
const game_id = parseInt(req.params.game_id);
const game = products.find(game => game.id === game_id);
if (game) {
res.json(game);
} else {
res.status(404).json({error: ‘Game not found’});
}
});
// … 其他路由
app.listen(3000, () => console.log(‘Server started on port 3000’));
Java (Spring Boot)
首先,你需要创建一个Spring Boot项目并添加必要的依赖。以下是简化的Controller部分:
java
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping(“/games”)
public class GameController {
private List<Game> products = Arrays.asList(
new Game(1, "Game 1", 9.99),
new Game(2, "Game 2", 19.99)
// ... 更多游戏
);
@GetMapping
public List<Game> getGames() {
return products;
}
@GetMapping("/{gameId}")
public Game getGame(@PathVariable int gameId) {
for (Game game : products) {
if (game.getId() == gameId) {
return game;
}
}
throw new ResourceNotFoundException("Game not found");
}
// 自定义异常类,用于处理未找到资源的情况
@ResponseStatus(value = HttpStatus.NOT_FOUND)
class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
// Game类(简单示例)
static class Game {
private int id;
private String name;
private double price;
// 构造函数、getter和setter等...
}
}
注意:以上代码只是非常简化的示例,用于展示游戏商城的基本结构。在实际项目中,你需要考虑更多的细节,如数据库交互、用户认证、错误处理、支付集成等。