2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Go + TypeScript構成でチュートリアルWebアプリ作ってみる(1) ~サーバ起動まで~

Last updated at Posted at 2025-06-12

初めに

次回の記事

Go + TypeScript構成でチュートリアルWebアプリ作ってみる(2) ~バックエンドにCRUDのAPI作成~

環境構築

// 開発フォルダの作成
mkdir my-project
cd my-project

// バックエンド(Go)のセットアップ
// Goモジュール初期化
mkdir backend
cd backend
go mod init app-backend

// HTTPフレームワークのインストール(例:Gin)
go get -u github.com/gin-gonic/gin

// フロントエンド(TypeScript)のセットアップ
// フォルダ作成&Node.jsプロジェクト初期化
cd ..
mkdir frontend
cd frontend
npm init -y

// 必要なパッケージをインストール
// TypeScript本体・ビルドツール
npm install typescript vite @vitejs/plugin-react react react-dom
npm install -D @types/react @types/react-dom

// TypeScript初期設定
npx tsc --init

簡単なGoサーバーの作成

backend/main.goの作成

package main

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// 構造体定義
type Task struct {
	ID   int    `json:"id"`
	Text string `json:"text"`
}

// 初期タスクの生成
var tasks = []Task{
	{ID: 1, Text: "Sample Task"},
}

func main() {
	r := gin.Default()

	// portが異なるフロントからの接続許可
	r.Use(cors.Default())

	r.GET("/tasks", func(c *gin.Context) {
		c.JSON(200, tasks)
	})

	// バックは8080で受付
	r.Run(":8080")
}

疎通確認

go run ./main.go
localhost:8080/tasks にアクセスしてみて、タスクが表示されればOK

image.png

フロントを介して表示してみる

vite.config.ts(ビルドツールの設定ファイル) を作成

frontend/vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// フロントはport3000で受付
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
  },
})

Reactのメインコンポーネントを定義

frontend/src/App.tsx

import React, { useEffect, useState } from "react";

// タスクの型定義
type Task = {
  id: number;
  text: string;
};

export const App = () => {
  const [tasks, setTasks] = useState<Task[]>([]);

  // バックエンドからタスクのレコードをJSONで取得
  useEffect(() => {
    fetch("http://localhost:8080/tasks")
      .then((res) => res.json())
      .then((data) => {
        setTasks(data);
      })
      .catch((err) => {
        console.error("API fetch error:", err);
      });
  }, []);

  // ループさせて表示
  return (
    <div>
      <h1>Sample</h1>
      <ul>
        {tasks.map((task) => (
          <li key={task.id}>{task.text}</li>
        ))}
      </ul>
    </div>
  );
};

Reactアプリのエントリーポイント作成

frontend/src/main.tsx

import React from "react"; // React本体をインポート
import ReactDOM from "react-dom/client"; // DOMレンダリング用APIをインポート
import { App } from "./App"; // Appをインポート

// HTMLファイル内の <div id="root"></div> 要素を取得し、Reactアプリをマウントするためのルートを作成
const root = ReactDOM.createRoot(document.getElementById("root")!);

// App コンポーネントをレンダリング
root.render(<App />);

最初に読み込まれるHTML

frontend/index.html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>Sample</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

疎通確認

npx vite
localhost:3000 にアクセスしてみて、バックエンドのタスクが表示されればOK

image.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?