Use Golang to build RESTful API and connect to MySQL database: install Golang, MySQL driver and create project. Define API handlers, including getting all users and specific users. Connect to the MySQL database through the sql.Open function. Use db.Query and db.QueryRow to get data from the database. Use json.NewEncoder to write JSON responses. Optional: Provide code examples for creating new users.
How to use Golang to build a RESTful API and connect to the MySQL database
Introduction
RESTful API is a type of API based on the HTTP protocol that simplifies the interaction between the client and the server. Building RESTful APIs using Golang takes full advantage of its high performance and concurrency. This article will guide you on how to use Golang to build a RESTful API and connect to a MySQL database.
Prerequisites
github. com/go-sql-driver/mysql
)Build RESTful API
go mod init <project name>
command to create a new project. go get -u github.com/go-sql-driver/mysql
command to install the MySQL driver. main.go
file: package main import ( "database/sql" "log" "net/http" "strconv" "github.com/go-sql-driver/mysql" ) const ( user = "root" password = "" host = "localhost" port = 3306 database = "my_db" ) var db *sql.DB func init() { dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true", user, password, host, port, database) var err error db, err = sql.Open("mysql", dsn) if err != nil { log.Fatal(err) } } func main() { http.HandleFunc("/users", handleUsers) http.HandleFunc("/users/", handleUser) log.Fatal(http.ListenAndServe(":8080", nil)) }
sql.Open
function to connect to the MySQL database. http.HandleFunc
function to define two route handlers: /users
and /users/ :id
. http.ListenAndServe
function to start the server. Handling user requests
/users
handler, Use the db.Query
function to get all users from the database. /users/:id
handler, use the db.QueryRow
function to get a specific user from the database. json.NewEncoder
function to encode user data into JSON and write it into the HTTP response. Practical case
Assume that your MySQL database has a table named users
, with the following structure:
CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, PRIMARY KEY (id) );
You can use the following code to create a new user and add it to the database:
func handleCreateUser(w http.ResponseWriter, r *http.Request) { var user User if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, "Invalid JSON", http.StatusBadRequest) return } stmt, err := db.Prepare("INSERT INTO users (name, email) VALUES (?, ?);") if err != nil { log.Fatal(err) } defer stmt.Close() res, err := stmt.Exec(user.Name, user.Email) if err != nil { log.Fatal(err) } id, err := res.LastInsertId() if err != nil { log.Fatal(err) } user.ID = int(id) json.NewEncoder(w).Encode(user) }
Note: Don’t forget to update the database connection information and the handling mechanism related to cross-domain requests.
The above is the detailed content of How to use Golang to build a RESTful API and connect to a MySQL database?. For more information, please follow other related articles on the PHP Chinese website!