Home  >  Article  >  Backend Development  >  Golang implements photo wall

Golang implements photo wall

WBOY
WBOYOriginal
2023-05-13 10:36:07546browse

With the popularity of mobile Internet, people’s demand for photos is increasing. Whether it is an event, travel, or party, taking photos is indispensable. How to display these photos has also become a concern. An application that implements the photo wall function came into being. Today we will introduce the process of implementing the photo wall using golang language.

1. Golang language features

golang is an open source language developed by Google. The main features are as follows:

  1. Efficiency: Golang’s compilation speed is very fast and has significant advantages compared with C and Java.
  2. Memory management: Golang’s memory management is automatically completed by the compiler, and programmers do not need to manually manage memory.
  3. Concurrent programming: golang provides powerful support for concurrent programming, which can better exert application performance in the case of multi-core CPUs or multiple servers.
  4. Simplicity: The syntax of golang language is concise and easy to understand, allowing programmers to get started faster.

2. Design Ideas

When implementing the photo wall function, we need to consider the following aspects:

  1. Upload of photos: Users need to be able to When uploading your own photos, you also need to be able to tag the photos for easy classification and display.
  2. Display of photos: Uploaded photos should be classified and displayed according to tags, and users can select tags to view.
  3. Database storage: The photo wall needs to store the photo data uploaded by users, and we need to use a database for data storage.

3. Technical implementation

  1. Environment setup

Before we start, we need to prepare the environment first. We can download the golang installation package from golang's official website. After the installation is complete, enter the following code in the terminal to verify whether the installation is successful:

$ go version
  1. Database Design

We need Design a database to store pictures uploaded by users, so we need to design a table containing the following fields:

  • id (photo id, primary key)
  • name (photo name)
  • path (photo path, the storage path of the picture on the server)
  • tag (tag)

The above fields are the photo information we need to store.

  1. Upload photos

We need to implement the function of uploading photos on the client so that users can freely upload photos and tag them. First, we need to implement the photo upload function on the front-end page, which can be implemented using the HTML5 File API. The following is a code example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>照片上传</title>
    </head>
    <body>
        <input type="file" id="file">
        <input type="text" id="tag">
        <button onclick="upload()">上传</button>
    </body>
    <script>
        function upload() {
            var file = document.getElementById("file").files[0];
            var tag = document.getElementById("tag").value;
            var formData = new FormData();
            formData.append("file", file);
            formData.append("tag", tag);
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/upload", true);
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert("上传成功");
                } else {
                    alert("上传失败");
                }
            }
            xhr.send(formData);
        }
    </script>
</html>

On the server side, we need to use the http package provided by golang to implement the photo upload function. The following is a sample code:

func upload(w http.ResponseWriter, r *http.Request) {
    file, handler, err := r.FormFile("file")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    tag := r.FormValue("tag")
    fileName := handler.Filename
    f, err := os.OpenFile("./upload/"+fileName, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    io.Copy(f, file)
    insertData(fileName, "./upload/"+fileName, tag)
    w.Write([]byte("上传成功"))
}

In the above code, we use os.OpenFile() to save the uploaded photos on the local disk of the server, and then insert the photo information into the database.

  1. Display photos

We categorize and display photos based on the tags of photos uploaded by users. On the server side, we need to query the database, filter photos with specific tags, and return them to the client for display. The following is a sample code:

func getPhotos(w http.ResponseWriter, r *http.Request) {
    tag := r.FormValue("tag")
    var photos []Photo
    if tag == "" {
        db.Find(&photos)
    } else {
        db.Where("tag=?", tag).Find(&photos)
    }
    result := make([]string, len(photos))
    for i, photo := range photos {
        result[i] = photo.Path
    }
    jsonBytes, err := json.Marshal(result)
    if err != nil {
        fmt.Println(err)
        return
    }
    w.Write(jsonBytes)
}

In the above code, we first query the database based on the tag requested by the user and obtain a list of photo paths that meet the conditions. Then convert the photo path list into json format and return it to the client.

On the front-end page, we can use the Masonry.js library to implement the layout of the photo wall. The following is the sample code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>照片墙</title>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js"></script>
        <style>
            .photo {
                width: 200px;
                margin: 10px;
            }
        </style>
    </head>
    <body>
        <input type="text" id="tag">
        <button onclick="getPhotos()">搜索</button>
        <div id="container">
            <div class="grid-sizer"></div>
        </div>
    </body>
    <script>
        function getPhotos() {
            var tag = document.getElementById("tag").value;
            $.ajax({
                url: "/getPhotos",
                type: "GET",
                data: {"tag": tag},
                success: function (data) {
                    var html = "";
                    for (var i = 0; i < data.length; i++) {
                        html += '<div class="photo"><img src="' + data[i] + '"></div>';
                    }
                    $("#container").html(html);
                    var $container = $('#container');
                    $container.imagesLoaded(function () {
                        $container.masonry({
                            itemSelector: ".photo",
                            columnWidth: ".grid-sizer",
                            gutter: 10
                        });
                    });
                }
            });
        }
    </script>
</html>

In the client, we send an ajax request to obtain the specified label Photo list. Then the photo list is dynamically generated into photo nodes, and the Masonry.js library is used to implement a photo wall-style layout.

5. Summary

In this implementation, we used golang language to implement the photo wall function. By implementing the process of uploading and displaying photos, we learned about the golang language's support for file operations and database operations. As an emerging programming language, golang not only has advantages in syntax simplicity and efficiency, but also supports concurrent programming, and has its own place in application scenarios that deal with high concurrency and large amounts of data. In the future, we can continue to learn, explore, and apply the golang language in depth.

The above is the detailed content of Golang implements photo wall. 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
Previous article:Centos 7 install golangNext article:Centos 7 install golang