Home  >  Article  >  Backend Development  >  How to use Golang to build a RESTful API and connect to a MySQL database?

How to use Golang to build a RESTful API and connect to a MySQL database?

WBOY
WBOYOriginal
2024-06-05 19:22:011013browse

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.

如何使用 Golang 构建 RESTful API 并连接 MySQL 数据库?

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

  • Install Golang (version 1.18 or higher)
  • MySQL database and MySQL driver (github. com/go-sql-driver/mysql)
  • Text editor or IDE (such as Visual Studio Code)

Build RESTful API

  1. Create a new project: Use the go mod init ea05abe187ada2ae937559e33ea428f2 command to create a new project.
  2. Install the MySQL driver: Use the go get -u github.com/go-sql-driver/mysql command to install the MySQL driver.
  3. Write the API handler: Write the following API handler in the 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))
}
  1. Connect to the MySQL database: Use the sql.Open function to connect to the MySQL database.
  2. Define route handlers: Use the http.HandleFunc function to define two route handlers: /users and /users/ :id.
  3. Running the server: Use the http.ListenAndServe function to start the server.

Handling user requests

  1. Get all users: In /users handler, Use the db.Query function to get all users from the database.
  2. Get a specific user: In the /users/:id handler, use the db.QueryRow function to get a specific user from the database.
  3. Writing the response: Use the 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn