Hey there, fellow Go enthusiast! Ready to dive into the world of MySQL API integration? You're in the right place. We'll be using the awesome go-sql-driver/mysql
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
If you're all set, let's move on to the fun stuff!
First things first, let's get our project structure sorted:
mkdir mysql-api-project cd mysql-api-project go mod init github.com/yourusername/mysql-api-project
Easy peasy, right?
Time to grab the packages we need:
go get -u github.com/go-sql-driver/mysql go get -u github.com/gorilla/mux
We're using gorilla/mux
for routing because, well, it's fantastic!
Let's get connected to our MySQL database:
package main import ( "database/sql" "log" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname") if err != nil { log.Fatal(err) } defer db.Close() // Check the connection err = db.Ping() if err != nil { log.Fatal(err) } log.Println("Connected to MySQL!") }
Don't forget to replace user
, password
, and dbname
with your actual MySQL credentials!
Now, let's set up some routes:
package main import ( "github.com/gorilla/mux" "net/http" ) func main() { // ... database connection code ... r := mux.NewRouter() r.HandleFunc("/users", getUsers).Methods("GET") r.HandleFunc("/users", createUser).Methods("POST") r.HandleFunc("/users/{id}", getUser).Methods("GET") r.HandleFunc("/users/{id}", updateUser).Methods("PUT") r.HandleFunc("/users/{id}", deleteUser).Methods("DELETE") log.Fatal(http.ListenAndServe(":8080", r)) }
Let's implement those handlers we just defined:
func getUsers(w http.ResponseWriter, r *http.Request) { rows, err := db.Query("SELECT * FROM users") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer rows.Close() // Process rows... } func createUser(w http.ResponseWriter, r *http.Request) { // Parse request body stmt, err := db.Prepare("INSERT INTO users(name, email) VALUES(?, ?)") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() // Execute the statement... } // Implement getUser, updateUser, and deleteUser similarly...
Always check for errors and log them:
if err != nil { log.Printf("Error: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return }
Time to take your API for a spin! Use curl or Postman to test each endpoint. For example:
curl http://localhost:8080/users
Here are some pro tips to level up your API:
sql.DB
does this for you!)And there you have it! You've just built a MySQL API integration in Go. Pretty cool, right? Remember, this is just the beginning. There's always room for improvement, so keep exploring and refining your code.
Want to dive deeper? Check out these resources:
Now go forth and build amazing things with Go and MySQL! You've got this! 🚀