package main
import (
"database/sql"
"log"
// Import the SQLite driver anonymously to initialize it
// without directly referencing
_ "github.com/mattn/go-sqlite3"
)
// Declare a global variable to hold the database connection pool
var db *sql.DB
// initDB initializes the database connection and creates
// the 'notes' table if it doesn't exist
func initDB() {
var err error
// Open a connection to the SQLite database file named "notes.db"
db, err = sql.Open("sqlite3", "./notes.db")
if err != nil {
// Log any error that occurs and terminate the program
log.Fatal(err)
}
// SQL statement to create the notes table if it doesn't exist
createTable := `
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT
);`
// Execute the SQL statement to create the table
_, err = db.Exec(createTable)
if err != nil {
// Log any error that occurs while executing the SQL statement
// and terminate the program
log.Fatal(err)
}
}
以下の手順に従って、ファイル作成のプロセスを進めていきます。
Go ファイルを作成する
Go ファイルを作成するには、次のいずれかのオプションを使用します。
プロジェクト ツールウィンドウで、プロジェクトの親フォルダーを右クリックし、 新規 | Go ファイル を選択します。
プロジェクトの親フォルダーをクリックし、 Alt+Insert を押して、 Go ファイル を選択します。
func main() {
// Initialize the database
initDB()
// Ensure the database connection is closed when the main function exits
defer db.Close()
// Set up HTTP handlers for different routes
http.HandleFunc("/", indexHandler) // Route for the homepage
http.HandleFunc("/add", addHandler) // Route for adding a new note
http.HandleFunc("/delete", deleteHandler) // Route for deleting a note
// Log the server start and listen on port 8080
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
テンプレートの実行: 取得したメモを使用してテンプレートを実行し、応答ライター w に HTML をレンダリングします。
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve all notes from the database
notes, err := GetNotes()
if err != nil {
// Send an internal server error response if something goes wrong
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Parse the HTML template file
tmpl, err := template.ParseFiles("index.html")
if err != nil {
// Send an internal server error response if the template cannot be parsed
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the template with the notes data
tmpl.Execute(w, notes)
}
func addHandler(w http.ResponseWriter, r *http.Request) {
// Only handle POST requests
if r.Method == "POST" {
// Get the title and content from the form values
title := r.FormValue("title")
content := r.FormValue("content")
// Create a new note with the provided title and content
CreateNote(title, content)
}
// Redirect the user back to the homepage after adding the note
http.Redirect(w, r, "/", http.StatusSeeOther)
}
機能: 削除ハンドラー
削除ハンドラーは、データベースからメモを削除します。 このハンドラーは次の処理を実行します。
ID 変換: ID フォームの値を整数に変換します。 変換が失敗した場合は、不正な要求応答が送信されます。
メモの削除: DeleteNote を呼び出して、指定された ID のメモをデータベースから削除します。
リダイレクト: メモを削除した後、ユーザーをホームページにリダイレクトします。
func deleteHandler(w http.ResponseWriter, r *http.Request) {
// Convert the ID from the form value to an integer
id, err := strconv.Atoi(r.FormValue("id"))
if err != nil {
// Send a bad request response if the ID is not valid
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
// Delete the note with the given ID
DeleteNote(id)
// Redirect the user back to the homepage after deleting the note
http.Redirect(w, r, "/", http.StatusSeeOther)
}
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
)
// main function is the entry point of the program
func main() {
// Initialize the database
initDB()
// Ensure the database connection is closed when the main function exits
defer db.Close()
// Set up HTTP handlers for different routes
http.HandleFunc("/", indexHandler) // Route for the homepage
http.HandleFunc("/add", addHandler) // Route for adding a new note
http.HandleFunc("/delete", deleteHandler) // Route for deleting a note
// Log the server start and listen on port 8080
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// indexHandler handles the requests to the homepage
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve all notes from the database
notes, err := GetNotes()
if err != nil {
// Send an internal server error response if something goes
// wrong
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Parse the HTML template file
tmpl, err := template.ParseFiles("index.html")
if err != nil {
// Send an internal server error response if the template
// cannot be parsed
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the template with the notes data
tmpl.Execute(w, notes)
}
// addHandler handles the requests to add a new note
func addHandler(w http.ResponseWriter, r *http.Request) {
// Only handle POST requests
if r.Method == "POST" {
// Get the title and content from the form values
title := r.FormValue("title")
content := r.FormValue("content")
// Create a new note with the provided title and content
CreateNote(title, content)
}
// Redirect the user back to the homepage after adding the note
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// deleteHandler handles the requests to delete a note
func deleteHandler(w http.ResponseWriter, r *http.Request) {
// Convert the ID from the form value to an integer
id, err := strconv.Atoi(r.FormValue("id"))
if err != nil {
// Send a bad request response if the ID is not valid
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
// Delete the note with the given ID
DeleteNote(id)
// Redirect the user back to the homepage after deleting the note
http.Redirect(w, r, "/", http.StatusSeeOther)
}
ステップ 6: HTML フォームを作成する
次に、メモを追加および削除するためのフォームを含む index.html という新しいファイルを作成しましょう。 このファイルは html/template パッケージを使用します。 Go の html/template パッケージは、テンプレートを解析して実行する機能を提供します。 {{range .}} や {{.Title}} などのプレースホルダーは Go のテンプレート構文の一部であり、HTML に動的なコンテンツを挿入できます。
// Parse the HTML template file
tmpl, err := template.ParseFiles("index.html")
if err != nil {
// Send an internal server error response if the template cannot be parsed
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the template with the notes data
tmpl.Execute(w, notes)