Connexion de votre API Go à une base de données PostgreSQL
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!
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

Video Face Swap
Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds











Golang est meilleur que Python en termes de performances et d'évolutivité. 1) Les caractéristiques de type compilation de Golang et le modèle de concurrence efficace le font bien fonctionner dans des scénarios de concurrence élevés. 2) Python, en tant que langue interprétée, s'exécute lentement, mais peut optimiser les performances via des outils tels que Cython.

Golang est meilleur que C en concurrence, tandis que C est meilleur que Golang en vitesse brute. 1) Golang obtient une concurrence efficace par le goroutine et le canal, ce qui convient à la gestion d'un grand nombre de tâches simultanées. 2) C Grâce à l'optimisation du compilateur et à la bibliothèque standard, il offre des performances élevées près du matériel, adaptées aux applications qui nécessitent une optimisation extrême.

Golang convient au développement rapide et aux scénarios simultanés, et C convient aux scénarios où des performances extrêmes et un contrôle de bas niveau sont nécessaires. 1) Golang améliore les performances grâce à des mécanismes de collecte et de concurrence des ordures, et convient au développement de services Web à haute concurrence. 2) C réalise les performances ultimes grâce à la gestion manuelle de la mémoire et à l'optimisation du compilateur, et convient au développement du système intégré.

GOIMIMPACTSDEVENCEMENTSPOSITIVEMENTS INSPECT, EFFICACTION ET APPLICATION.1) VITESSE: GOCOMPILESQUICKLYANDRUNSEFFIÉMENT, IDEALFORLARGEPROROSTS.2) Efficacité: ITSCOMPEHENSIVESTANDARDLIBRARYREDUCEEXTERNEDENDENCES, EnhancingDevelovefficiency.3) Simplicité: Simplicité: Implicité de la manière

GOISIDEALFORBEGINNERNERS et combinant pour pourcloudandNetWorkServicesDuetOtssimplicity, Efficiency, andCurrencyFeatures.1) InstallgofromTheofficialwebsiteandverifywith'goversion'..2)

Golang et Python ont chacun leurs propres avantages: Golang convient aux performances élevées et à la programmation simultanée, tandis que Python convient à la science des données et au développement Web. Golang est connu pour son modèle de concurrence et ses performances efficaces, tandis que Python est connu pour sa syntaxe concise et son écosystème de bibliothèque riche.

C est plus adapté aux scénarios où le contrôle direct des ressources matérielles et une optimisation élevée de performances sont nécessaires, tandis que Golang est plus adapté aux scénarios où un développement rapide et un traitement de concurrence élevé sont nécessaires. 1.C's Avantage est dans ses caractéristiques matérielles proches et à des capacités d'optimisation élevées, qui conviennent aux besoins de haute performance tels que le développement de jeux. 2. L'avantage de Golang réside dans sa syntaxe concise et son soutien à la concurrence naturelle, qui convient au développement élevé de services de concurrence.

Les différences de performance entre Golang et C se reflètent principalement dans la gestion de la mémoire, l'optimisation de la compilation et l'efficacité du temps d'exécution. 1) Le mécanisme de collecte des ordures de Golang est pratique mais peut affecter les performances, 2) la gestion manuelle de C et l'optimisation du compilateur sont plus efficaces dans l'informatique récursive.
