Slide 13
Slide 13 text
© DMM.com
Go開発の取り組み(プロジェクト構成)
13
課題1. 記述量増加
// Item構造体を定義
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
// 指定IDのアイテムを取得する関数
func getItem(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
var item Item
err := db.QueryRow("SELECT id, name, price FROM items WHERE id =
$1", id).Scan(&item.ID, &item.Name, &item.Price)
if err != nil {
http.Error(w, "Item not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(item)
}
// 指定IDのアイテムを取得する関数
function getItem($id) {
global $pdo;
$stmt = $pdo->prepare("SELECT id, name, price FROM items
WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
// APIの呼び出し処理
header('Content-Type: application/json');
echo json_encode(getItem($_GET['id']));
Go PHP