Alright, so we’ve got our Go API rolling, but it’s about time we gave it some long-term memory. This week, we’re connecting our API to PostgreSQL, so you can store all that precious data without losing it the second you shut down your app. Trust me, your users will thank you.
Why PostgreSQL?
PostgreSQL or “Postgres” for short, is the real deal when it comes to databases. Here’s why it’s the most popular DB:
Feature-Packed: Whether you want to store plain old text, JSON, or even complex geographical data, Postgres has got you covered. It’s also got full ACID compliance (read: it keeps your data consistent and safe) and enough fancy querying options to make any data nerd smile.
Open-Source and Free: That’s right—Postgres is totally free and open-source. Plus, it has an active community that’s constantly improving it, so you’ll never have to worry about it becoming outdated.
Scales Like a Pro: Whether you’re building a tiny app or a massive, data-chomping enterprise service, Postgres can handle it. It’s designed to scale, with parallel query execution and optimization magic to keep things running smoothly.
Built Like a Tank: With decades of development under its belt, Postgres is rock-solid. It gets regular updates, has a ton of security features, and is used in production by giants like Apple and Netflix.
Got all that? Cool, let’s hook it up to our Go API and start working some database magic!
Step 0: Setting Up PostgreSQL
If you don’t already have PostgreSQL installed, grab it here. Then let’s fire it up:
- Connect to PostgreSQL:
psql -U postgres
- Create a database:
CREATE DATABASE bookdb;
- Set up a table for our books:
\c bookdb; CREATE TABLE books ( id SERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL );
Now you’ve got a fresh database ready to go. Time to get Go talking to it!
Step 1: Connect Go to PostgreSQL
We’re using the pgx library for this one. It’s fast, it’s lightweight, and it gets the job done.
go get github.com/jackc/pgx/v5
Open up your main.go file and add this code to set up a connection to the database:
var db *pgxpool.Pool func connectDB() *pgxpool.Pool { url := "postgres://postgres:yourpassword@localhost:5432/bookdb" config, err := pgxpool.ParseConfig(url) if err != nil { log.Fatalf("Unable to parse DB config: %v\n", err) } dbpool, err := pgxpool.NewWithConfig(context.Background(), config) if err != nil { log.Fatalf("Unable to connect to database: %v\n", err) } return dbpool }
Replace yourpassword with your PostgreSQL password. This function connects to our bookdb database and returns a connection pool, which basically means our app will have a bunch of reusable connections ready to go. Efficiency, baby! ?
Step 2: Update the Main Function
Let’s make sure our database connection fires up when our server does:
func main() { db = connectDB() defer db.Close() // Initialize router and define routes here (as before) }
Step 3: CRUD Operations – Bringing in the Data
Alright, let’s add some functions to fetch, create, and manage books in our database.
Fetch All Books
func getBooks(w http.ResponseWriter, r *http.Request) { rows, err := db.Query(context.Background(), "SELECT id, title, author FROM books") if err != nil { http.Error(w, "Database error", http.StatusInternalServerError) return } defer rows.Close() var books []Book for rows.Next() { var book Book err := rows.Scan(&book.ID, &book.Title, &book.Author) if err != nil { http.Error(w, "Error scanning row", http.StatusInternalServerError) return } books = append(books, book) } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(books) }
Add a New Book
func createBook(w http.ResponseWriter, r *http.Request) { var book Book err := json.NewDecoder(r.Body).Decode(&book) if err != nil { http.Error(w, "Bad request", http.StatusBadRequest) return } _, err = db.Exec(context.Background(), "INSERT INTO books (title, author) VALUES ($1, $2)", book.Title, book.Author) if err != nil { http.Error(w, "Error inserting book", http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(book) }
Step 4: Protecting the Routes with Middleware
We want to make sure only authenticated users can access our new database-powered endpoints. Use the authenticate middleware from Week 2, and you’re all set!
func main() { db = connectDB() defer db.Close() r := mux.NewRouter() r.HandleFunc("/login", login).Methods("POST") r.Handle("/books", authenticate(http.HandlerFunc(getBooks))).Methods("GET") r.Handle("/books", authenticate(http.HandlerFunc(createBook))).Methods("POST") fmt.Println("Server started on port :8000") log.Fatal(http.ListenAndServe(":8000", r)) }
Testing It Out
Let’s put this thing to the test:
- Add a new book:
curl -X POST http://localhost:8000/books -d '{"title": "1984", "author": "George Orwell"}' -H "Content-Type: application/json"
- Fetch all books:
curl http://localhost:8000/books
And boom! You’ve got a Go API with PostgreSQL, ready to handle some real data.
What’s Next?
Next time, we’ll make our API even slicker with some custom middleware for logging and error handling. Stay tuned for more!
以上是將 Go API 連接到 PostgreSQL 資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

本文討論了GO的反思軟件包,用於運行時操作代碼,對序列化,通用編程等有益。它警告性能成本,例如較慢的執行和更高的內存使用,建議明智的使用和最佳

本文討論了GO中使用表驅動的測試,該方法使用測試用例表來測試具有多個輸入和結果的功能。它突出了諸如提高的可讀性,降低重複,可伸縮性,一致性和A

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6
視覺化網頁開發工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具