- Python (使用 Flask 框架)hongjet.cn
Python 是非常适合快速开发 web 应用的语言,Flask 是一个轻量级的 web 框架。
python
from flask import Flask, jsonify
app = Flask(name)
假设的游戏数据
games = [
{“id”: 1, “name”: “游戏A”, “price”: 99.99},
{“id”: 2, “name”: “游戏B”, “price”: 149.99},
{“id”: 3, “name”: “游戏C”, “price”: 49.99}
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id/buy’, methods=[‘POST’])
def buy_game(game_id):
# 假设的购买逻辑(实际上需要支付网关等)
game_found = next((game for game in games if game[‘id’] == game_id), None)
if game_found:
# 这里只是模拟购买,实际中你需要处理支付和库存
return jsonify({“success”: True, “message”: f"购买了 {game_found[‘name’]}"}), 200
else:
return jsonify({“success”: False, “message”: “游戏未找到”}), 404
if name == ‘main’:
app.run(debug=True)
2. JavaScript (Node.js + Express)
Node.js 是基于 Chrome V8 引擎的 JavaScript 运行时环境,Express 是一个灵活的 Node.js web 应用框架。
javascript
const express = require(‘express’);
const app = express();
const port = 3000;
// 假设的游戏数据
const games = [
{ id: 1, name: ‘游戏A’, price: 99.99 },
{ id: 2, name: ‘游戏B’, price: 149.99 },
{ id: 3, name: ‘游戏C’, price: 49.99 }
];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.post(‘/games/:gameId/buy’, (req, res) => {
const gameId = parseInt(req.params.gameId, 10);
const game = games.find(game => game.id === gameId);
if (game) {
// 假设购买成功
res.json({ success: true, message: 购买了 ${game.name}
});
} else {
res.status(404).json({ success: false, message: ‘游戏未找到’ });
}
});
app.listen(port, () => {
console.log(游戏商城运行在 http://localhost:${port}/
);
});
3. Java (Spring Boot)
Spring Boot 是 Java 的一个流行的框架,用于创建微服务。
java
// 注意:这里只展示控制器部分的伪代码
@RestController
@RequestMapping(“/games”)
public class GameController {
// 假设的游戏列表(实际中应从数据库获取)
private List<Game> games = Arrays.asList(
new Game(1, "游戏A", 99.99),
new Game(2, "游戏B", 149.99),
new Game(3, "游戏C", 49.99)
);
@GetMapping
public List<Game> getGames() {
return games;
}
@PostMapping("/{gameId}/buy")
public ResponseEntity<?> buyGame(@PathVariable Long gameId) {
Game game = games.stream().filter(g -> g.getId().equals(gameId)).findFirst().orElse(null);
if (game != null) {
// 假设购买逻辑
return ResponseEntity.ok("购买了 " + game.getName());
} else {
return ResponseEntity.notFound().body("游戏未找到");
}
}
// Game 类省略...
}