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!
The above is the detailed content of Connecting Your Go API to a PostgreSQL Database. For more information, please follow other related articles on the PHP Chinese website!

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool