Open2
Go + React 構成の試作

概要
- Go + React構成メモです。
[ 公開 2025/06/27 ]
環境
- go version go1.24.4
- react 19
- react-dom 19
- esbuild
- node 20
書いたコード
- dev-start
npm run build
- Go-build
go build
- react1/server.go
- http.StripPrefix: public 指定する例です。
fs := http.FileServer(http.Dir("./public"))
// "/public/" プレフィックスを外して、中身を返すようにする
http.Handle("/public/", http.StripPrefix("/public/", fs))
- templates フォルダ内の、index.html から HTML取り出す。
func helloHandler(w http.ResponseWriter, r *http.Request) {
var err error
homeData := HomeData{"hello"}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fp := path.Join("templates", "index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, homeData); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
- react1/templates/index.html
- client.js : ビルドされた Reactのファイル
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ .Title }}</title>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>
<body>
<div id='app'></div>
<script type='module' src='/public/client.js'></script>
</body>
</html>

Postgres + Go API の例
- 今回は、postgres + API の例になります
書いたコード
環境
- go version go1.24.4
- postgres 17
- build
go build
- http7/server.go
- ルーティング , CRUD的なエンドポイントを追加。
func main() {
db, err := connectDB()
if err != nil {
log.Fatal(err)
}
defer db.Close()
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/list", listTodosHandler)
http.HandleFunc("/create", createTodoHandler)
http.HandleFunc("/delete", deleteTodoHandler)
http.HandleFunc("/update", updateTodoHandler)
fmt.Println("Server running on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
- Get のテスト
curl http://localhost:8080/list