How to use Go language to develop the restaurant reservation function of the ordering system

王林
Release: 2023-11-01 17:18:57
Original
566 people have browsed it

How to use Go language to develop the restaurant reservation function of the ordering system

How to use Go language to develop the restaurant reservation function of the ordering system, specific code examples are needed

The restaurant reservation function is a very important part of the modern ordering system. It allows customers to reserve a dining time in the restaurant in advance, effectively avoiding waiting for a table and improving the customer's dining experience. In this article, we will use Go language to develop a simple restaurant reservation function.

First, we need to create a database to store restaurant information and reservation order data. We can use MySQL as the database management system, create a database named "restaurant", and create two tables in it called "restaurants" and "reservations".

The structure of the restaurants table is as follows:

CREATE TABLE restaurants (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    address VARCHAR(255) NOT NULL,
    capacity INT NOT NULL,
    available_time_start TIME NOT NULL,
    available_time_end TIME NOT NULL
);
Copy after login

The structure of the reservations table is as follows:

CREATE TABLE reservations (
    id INT PRIMARY KEY AUTO_INCREMENT,
    restaurant_id INT NOT NULL,
    guest_name VARCHAR(255) NOT NULL,
    reservation_time DATETIME NOT NULL,
    FOREIGN KEY (restaurant_id) REFERENCES restaurants(id)
);
Copy after login

Next, we will use the Go language to develop the restaurant reservation function of the ordering system. First, we need to create a restaurant structure to represent the restaurant's information, including the restaurant's name, address, capacity, and available time periods.

type Restaurant struct {
    ID               int
    Name             string
    Address          string
    Capacity         int
    AvailableTimeStart time.Time
    AvailableTimeEnd   time.Time
}
Copy after login

We also need to create a reservation structure to represent the reservation order information, including the reserved restaurant ID, customer name, reservation time, etc.

type Reservation struct {
    ID               int
    RestaurantID     int
    GuestName        string
    ReservationTime  time.Time
}
Copy after login

Next, we need to implement some database operation functions, including querying all restaurants, querying available restaurants, querying reservation orders, adding reservation orders, etc.

First, we create a db variable to store the database connection.

var db *sql.DB
Copy after login

In the main function, we need to open the database connection.

func main() {
    var err error
    db, err = sql.Open("mysql", "root:password@tcp(localhost:3306)/restaurant")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // 运行HTTP服务器
    http.HandleFunc("/restaurants", getRestaurantsHandler)
    http.HandleFunc("/available-restaurants", getAvailableRestaurantsHandler)
    http.HandleFunc("/reservations", getReservationsHandler)
    http.HandleFunc("/reserve", addReservationHandler)

    log.Fatal(http.ListenAndServe(":8080", nil))
}
Copy after login

Next, let’s implement some database operation functions.

First, the function to query all restaurants is as follows:

func getRestaurantsHandler(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query("SELECT * FROM restaurants")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var restaurants []Restaurant
    for rows.Next() {
        var restaurant Restaurant
        err := rows.Scan(&restaurant.ID, &restaurant.Name, &restaurant.Address, &restaurant.Capacity, &restaurant.AvailableTimeStart, &restaurant.AvailableTimeEnd)
        if err != nil {
            log.Fatal(err)
        }
        restaurants = append(restaurants, restaurant)
    }

    json.NewEncoder(w).Encode(restaurants)
}
Copy after login

Next, the function to query available restaurants is as follows:

func getAvailableRestaurantsHandler(w http.ResponseWriter, r *http.Request) {
    currentTime := time.Now()
    rows, err := db.Query("SELECT * FROM restaurants WHERE available_time_start <= ? AND available_time_end >= ?", currentTime, currentTime)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var restaurants []Restaurant
    for rows.Next() {
        var restaurant Restaurant
        err := rows.Scan(&restaurant.ID, &restaurant.Name, &restaurant.Address, &restaurant.Capacity, &restaurant.AvailableTimeStart, &restaurant.AvailableTimeEnd)
        if err != nil {
            log.Fatal(err)
        }
        restaurants = append(restaurants, restaurant)
    }

    json.NewEncoder(w).Encode(restaurants)
}
Copy after login

Then, the function to query reservation orders is as follows:

func getReservationsHandler(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query("SELECT * FROM reservations")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var reservations []Reservation
    for rows.Next() {
        var reservation Reservation
        err := rows.Scan(&reservation.ID, &reservation.RestaurantID, &reservation.GuestName, &reservation.ReservationTime)
        if err != nil {
            log.Fatal(err)
        }
        reservations = append(reservations, reservation)
    }

    json.NewEncoder(w).Encode(reservations)
}
Copy after login

Finally, the function to add a reservation order is as follows:

func addReservationHandler(w http.ResponseWriter, r *http.Request) {
    var reservation Reservation
    err := json.NewDecoder(r.Body).Decode(&reservation)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    stmt, err := db.Prepare("INSERT INTO reservations (restaurant_id, guest_name, reservation_time) VALUES (?, ?, ?)")
    if err != nil {
        log.Fatal(err)
    }
    defer stmt.Close()

    _, err = stmt.Exec(reservation.RestaurantID, reservation.GuestName, reservation.ReservationTime)
    if err != nil {
        log.Fatal(err)
    }

    w.WriteHeader(http.StatusOK)
}
Copy after login

Through the above steps, we have completed the restaurant reservation function of using the Go language to develop the ordering system. We can use tools such as Postman to test these HTTP interfaces, and can also provide corresponding data interfaces for front-end development. Of course, this is just a simple example, and it needs to be improved and perfected according to specific needs in actual development.

The above is the detailed content of How to use Go language to develop the restaurant reservation function of the ordering system. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!