vue.js 构建项目_如何使用Go和Vue.js构建照片供稿

vue.js 构建项目

By Neo Ighodaro

由新Ighodaro

Many social media applications allow users to upload photos and display them in a timeline for their followers to see.

许多社交媒体应用程序允许用户上传照片并在时间表中显示它们,以供其关注者查看。

In the past, you would have had to refresh your feed manually to see new photos uploaded to the timeline. However, with modern web technologies, you can see the updates in realtime without having to refresh the page manually.

过去,您必须手动刷新供稿才能查看上传到时间轴的新照片。 但是,使用现代Web技术,您可以实时查看更新,而不必手动刷新页面。

In this article, we will consider how you can build a realtime photo feed using Pusher Channels, GO and a little Vue.js. Pusher Channels helps you “easily build scalable in-app notifications, chat, realtime graphs, geotracking and more in your web & mobile apps with our hosted pub/sub messaging API.”

在本文中,我们将考虑如何使用Pusher Channels,GO和一些Vue.js构建实时照片供稿。 Pusher Channels可帮助您“通过托管的发布/订阅消息传递API在您的Web和移动应用程序中轻松构建可扩展的应用程序内通知,聊天,实时图形,地理位置跟踪等”。

This is a preview of what we will be building:

这是我们将要构建的预览:

先决条件 (Prerequisites)

Before we start building our application, make sure you have:

在开始构建应用程序之前,请确保您具有:

  • Basic knowledge of the Go programming language.

    Go编程语言的基本知识。

  • Basic JavaScript (Vue.js) knowledge.

    基本JavaScript(Vue.js)知识。
  • Go (version >= 0.10.x) installed on your machine. Check out the installation guide.

    在您的计算机上安装Go(版本> = 0.10.x)。 检查安装指南 。

  • SQLite (version >= 3.x) installed on your machine. Check out an installation guide.

    您的计算机上安装了SQLite(版本> = 3.x)。 查看安装指南 。

Let’s get started.

让我们开始吧。

获取Pusher Channels应用程序 (Getting a Pusher Channels application)

The first step will be to get a Pusher Channels application. We will need the application credentials for our realtime features to work.

第一步将是获得Pusher Channels应用程序。 我们将需要应用程序凭据才能使我们的实时功能正常工作。

Go to the Pusher website and create an account. After creating an account, you should create a new application. Follow the application creation wizard and then you should be given your application credentials, we will use this later in the article.

转到Pusher网站并创建一个帐户。 创建帐户后,您应该创建一个新的应用程序。 遵循应用程序创建向导,然后应为您提供应用程序凭据,我们将在本文后面使用它。

Now that we have our application, let’s move on to the next step

现在我们有了我们的应用程序,让我们继续下一步

创建我们的Go应用程序 (Creating our Go application)

The next thing we want to do is create the Go application. In your terminal, cd to your $GOPATH and create a new directory there.

我们要做的下一件事是创建Go应用程序。 在终端中, cd$GOPATH并在其中创建一个新目录。

$ cd $GOPATH/src$ mkdir gofoto$ cd gofoto

? It is recommended that you place the source code for your project in the src subdirectory (e.g., $GOPATH/src/your_project or $GOPATH/src/github.com/your_github_username/your_project.

? 建议您将项目的源代码放在s rc子目录中(例如,$ GOPATH/src/your_project或$ GOPATH/src/github.com/your_github_username/your_project.

Next, we will create some directories to organize our application a little:

接下来,我们将创建一些目录以稍微组织我们的应用程序:

$ mkdir database$ mkdir public$ mkdir public/uploads

This will create a database and public directory, and also an uploads directory inside the public directory. We will store our database file inside the database directory. We will keep our public files (HTML and images) inside the public and uploads directory.

这将创建一个databasepublic目录,并在公共目录内创建一个uploads目录。 我们将数据库文件存储在database目录中。 我们将公共文件(HTML和图像)保留在publicuploads目录中。

Create a new index.html file in the public directory that was created.

在已创建的public目录中创建一个新的index.html文件。

Now let’s create our first (and only) Go file for this article. We will keep everything simple by placing all our source code in a single file. Create a main.go file in the project root.

现在,让我们为本文创建第一个(也是唯一的)Go文件。 通过将所有源代码放在单个文件中,我们将使一切变得简单。 在项目根目录中创建一个main.go文件。

In the file paste the following:

在文件中粘贴以下内容:

package main
import (    "database/sql"    "io"    "net/http"    "os"
"github.com/labstack/echo"    "github.com/labstack/echo/middleware"
_ "github.com/mattn/go-sqlite3"    pusher "github.com/pusher/pusher-http-go")

This imports some packages we will be needing to work on our photo feed. We need the database/sql to run SQL queries. The io and os packages are for the file uploading process, and the net/http package is for our HTTP status codes.

这将导入一些需要在照片供稿上使用的软件包。 我们需要database/sql来运行SQL查询。 ioos软件包用于文件上传过程, net/http软件包用于我们的HTTP状态代码。

We have some other external packages we imported.

我们还有其他一些导入的外部软件包。

The labstack/echo package is the Echo framework that we will be using. We also have the mattn/go-sqlite3 package for SQLite. Finally, we imported the pusher/pusher-http-go package which we will use to trigger events to Pusher Channels.

labstack/echo软件包是我们将要使用的Echo框架 。 我们还为SQLite提供了mattn/go-sqlite3软件包。 最后,我们导入了pusher/pusher-http-go程序包,该程序包将用于触发事件到Pusher Channels。

导入外部Go包 (Importing external Go packages)

Before we continue, let’s pull in these packages using our terminal. Run the following commands below to pull the packages in:

在继续之前,让我们使用终端提取这些软件包。 运行以下命令以将软件包拉入:

$ go get github.com/labstack/echo$ go get github.com/labstack/echo/middleware$ go get github.com/mattn/go-sqlite3$ go get github.com/pusher/pusher-http-go

Note that the commands above will not return any confirmation output when it finishes installing the packages. If you want to confirm the packages were indeed installed you can just check the $GOPATH/src/github.com directory.

请注意,以上命令在完成安装软件包后将不会返回任何确认输出。 如果要确认软件包确实已安装,则可以检查$GOPATH/src/github.com目录。

Now that we have pulled in our packages, let’s create the main function. This is the function that will be the entry point of our application. In this function, we will set up our applications database, middleware, and routes.

现在,我们已经提取了包,让我们创建main函数。 这就是将成为我们应用程序入口点的功能。 在此功能中,我们将设置应用程序数据库,中间件和路由。

Open the main,go file and paste the following code:

打开main,go文件并粘贴以下代码:

func main() {    db := initialiseDatabase("database/database.sqlite")
migrateDatabase(db)
e := echo.New()
e.Use(middleware.Logger())    e.Use(middleware.Recover())
e.File("/", "public/index.html")    e.GET("/photos", getPhotos(db))    e.POST("/photos", uploadPhoto(db))    e.Static("/uploads", "public/uploads")
e.Logger.Fatal(e.Start(":9000"))}

In the code above, we instantiated our database using the file path to the database file. This will create the SQLite file if it did not already exist. We then run the migrateDatabase function which migrates the database.

在上面的代码中,我们使用数据库文件的文件路径实例化了数据库。 如果尚不存在,将创建SQLite文件。 然后,我们运行migrateDatabase函数来迁移数据库。

Next, we instantiate Echo and then register some middleware.

接下来,我们实例化Echo,然后注册一些中间件。

The logger middleware is helpful for logging information about the HTTP request. The recover middleware “recovers from panics anywhere in the chain, prints stack trace and handles the control to the centralized HTTPErrorHandler.”

记录器中间件有助于记录有关HTTP请求的信息。 恢复中间件 “从链中任何地方的紧急情况中恢复,打印堆栈跟踪并处理对集中式HTTPErrorHandler的控制。”

We then set up some routes to handle our requests. The first handler is the File handler. We use this to serve the index.html file. This will be the entry point to the application from the front end.

然后,我们设置一些路由来处理我们的请求。 第一个处理程序是File处理程序。 我们使用它来提供index.html文件。 这将是从前端到应用程序的入口点。

We also have the /photos route which accepts a POST and GET request. We need these routes to act like API endpoints that are used for uploading and displaying the photos.

我们也有/photos路由,它接受POSTGET请求。 我们需要这些路由来充当API端点,用于上传和显示照片。

The final handler is Static. We use this to return static files that are stored in the /uploads directory.

最终的处理程序是Static 。 我们使用它来返回存储在/uploads目录中的静态文件。

We finally use e.Start to start our Go web server running on port 9000. The port is not set in stone and you can choose any available and unused port you feel like.

最终,我们使用e.Start启动运行在端口9000上的Go Web服务器。该端口不是e.Start ,您可以选择任何可用的未使用的端口。

At this point, we have not created most of the functions we referenced in the main function so let’s do so now.

至此,我们还没有创建我们在main函数中引用的大多数函数,所以让我们现在开始吧。

创建我们的数据库管理功能 (Creating our database management functions)

In the main function we referenced an initialiseDatabase and migrateDatabase function. Let’s create them now. In the main.go file, paste the following functions above the main function:

main函数中,我们引用了initialiseDatabasemigrateDatabase函数。 现在创建它们。 在main.go文件中,将以下函数粘贴到main函数上方:

func initialiseDatabase(filepath string) *sql.DB {    db, err := sql.Open("sqlite3", filepath)
if err != nil || db == nil {        panic("Error connecting to database")    }
return db}
func migrateDatabase(db *sql.DB) {    sql := `        CREATE TABLE IF NOT EXISTS photos(                id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,                src VARCHAR NOT NULL        );    `
_, err := db.Exec(sql)
if err != nil {        panic(err)    }}

In the initialiseDatabase function, we create an instance of the SQLite database using the database file and return that instance. In the migrateDatabase function, we use the instance of the database returned in the previous function to execute the migration SQL.

initialiseDatabase函数中,我们使用数据库文件创建SQLite数据库的实例并返回该实例。 在migrateDatabase函数中,我们使用上一个函数返回的数据库实例来执行迁移SQL。

Let’s create the data structure for our photo and photo collection.

让我们为照片和照片集创建数据结构。

创建我们的数据结构 (Creating our data structures)

The next thing we will do is create the data structure for our object types. We will create a Photo structure and a PhotoCollection structure. The Photo struct will define how a typical photo will be represented while the PhotoCollection will define how a collection of photos will be represented.

接下来,我们将为对象类型创建数据结构。 我们将创建一个Photo结构和一个PhotoCollection结构。 Photo结构将定义典型照片的表示方式,而PhotoCollection将定义照片集合的表示方式。

Open the main.go file and paste the following code above the initialiseDatabase function:

打开main.go文件,并将以下代码粘贴到initialiseDatabase函数上方:

type Photo struct {    ID  int64  `json:"id"`    Src string `json:"src"`}
type PhotoCollection struct {    Photos []Photo `json:"items"`}

创建我们的路线处理函数 (Creating our route handler functions)

Next, let’s create the functions for our routes. Open the main.go file and paste the following file inside it:

接下来,让我们为路线创建功能。 打开main.go文件,并将以下文件粘贴到其中:

func getPhotos(db *sql.DB) echo.HandlerFunc {    return func(c echo.Context) error {        rows, err := db.Query("SELECT * FROM photos")
if err != nil {            panic(err)        }
defer rows.Close()
result := PhotoCollection{}
for rows.Next() {            photo := Photo{}
err2 := rows.Scan(&photo.ID, &photo.Src)
if err2 != nil {                panic(err2)            }
result.Photos = append(result.Photos, photo)        }
return c.JSON(http.StatusOK, result)    }}
func uploadPhoto(db *sql.DB) echo.HandlerFunc {    return func(c echo.Context) error {        file, err := c.FormFile("file")
if err != nil {            return err        }
src, err := file.Open()
if err != nil {            return err        }
defer src.Close()
filePath := "./public/uploads/" + file.Filename
fileSrc := "http://127.0.0.1:9000/uploads/" + file.Filename
dst, err := os.Create(filePath)
if err != nil {            panic(err)        }
defer dst.Close()
if _, err = io.Copy(dst, src); err != nil {            panic(err)        }
stmt, err := db.Prepare("INSERT INTO photos (src) VALUES(?)")
if err != nil {            panic(err)        }
defer stmt.Close()
result, err := stmt.Exec(fileSrc)
if err != nil {            panic(err)        }
insertedId, err := result.LastInsertId()
if err != nil {            panic(err)        }
photo := Photo{            Src: fileSrc,            ID:  insertedId,        }
return c.JSON(http.StatusOK, photo)    }}

In the getPhotos method, we are simply running the query to fetch all the photos from the database and returning them as a JSON response to the client.

getPhotos方法中,我们只是运行查询以从数据库中获取所有照片,并将它们作为JSON响应返回给客户端。

In the uploadPhoto method we first get the file to be uploaded then upload them to the server and then we run the query to insert a new record in the photos table with the newly uploaded photo. We also return a JSON response from that function.

uploadPhoto方法中,我们首先获取要上传的文件,然后将其上传到服务器,然后运行查询,以将带有新上传的照片的新记录插入到photos表中。 我们还从该函数返回JSON响应。

向我们的Go应用程序添加实时支持 (Adding realtime support to our Go application)

The next thing we want to do is trigger an event when a new photo is uploaded to the server. For this, we will be using the Pusher Go HTTP library.

我们要做的下一件事是在将新照片上传到服务器时触发事件。 为此,我们将使用Pusher Go HTTP库 。

In the main.go file paste the following above the type definitions for the Photo and PhotoCollection:

main.go文件中,将以下内容粘贴到PhotoPhotoCollection的类型定义PhotoCollection

var client = pusher.Client{    AppId:   "PUSHER_APP_ID",    Key:     "PUSHER_APP_KEY",    Secret:  "PUSHER_APP_SECRET",    Cluster: "PUSHER_APP_CLUSTER",    Secure:  true,}

This will create a new Pusher client instance. We can then use this instance to trigger notifications to different channels we want. Remember to replace the PUSHER_APP_* keys with the keys provided when you created your Pusher application earlier.

这将创建一个新的Pusher客户端实例。 然后,我们可以使用该实例来触发到我们想要的不同渠道的通知。 请记住,将PUSHER_APP_*键替换为PUSHER_APP_*创建Pusher应用程序时提供的键。

Next, go to the uploadPhoto function in the main.go file and right before the return statement at the bottom of the function, paste the following code:

接下来,转到main.go文件中的uploadPhoto函数,并在函数底部的return语句之前,粘贴以下代码:

client.Trigger("photo-stream", "new-photo", photo)

This is the code that triggers a new event when a new photo is uploaded to our application.

当新照片上传到我们的应用程序时,这是触发新事件的代码。

That will be all for our Go application. At this point, you can build your application and compile it into a binary using the go build command. However, for this tutorial we will just run the binary temporarily:

这将全部用于我们的Go应用程序。 此时,您可以构建应用程序,并使用go build命令将其编译为二进制文件。 但是,对于本教程,我们将仅临时运行二进制文件:

$ go run main.go

建立我们的前端 (Building our front end)

The next thing we want to do is build out our front end. We will be using the Vue.js framework and the Axios library to send requests.

我们要做的下一件事是扩展前端。 我们将使用Vue.js框架和Axios库发送请求。

Open the index.html file and in there paste the following code:

打开index.html文件,并在其中粘贴以下代码:

                Photo Feed        
Loading photos...
</div>

In the HTML file above we have defined the design for our photostream. We are using Bootstrap 4 and we included the CSS in the HTML above.

在上面HTML文件中,我们为照片流定义了设计。 我们正在使用Bootstrap 4,并且在上面HTML中包含了CSS。

We are also using the Axios library, Pusher library, and Vue framework. We included the links to the scripts at the bottom of the HTML document.

我们还使用了Axios库,Pusher库和Vue框架。 我们在HTML文档的底部包含了指向脚本的链接。

Next, let’s add the Vue.js code. In the HTML file, add the following code right before the closing body tag:

接下来,让我们添加Vue.js代码。 在HTML文件中,在结束body标签之前添加以下代码:

Above we created a Vue instance and stored the properties photos and loading. The photos property stores the photo list and the loading just holds a boolean that indicates if the photos are loading or not.

在上面,我们创建了一个Vue实例,并存储了photosloading属性。 photos属性存储照片列表,并且loading仅包含一个布尔值,指示是否正在加载照片。

In the mounted method we create an instance of our Pusher library. We then listen on the photo-stream channel for the new-photo event. When the event is triggered we append the new photo from the event to the photos list. We also send a GET request to /photos to fetch all the photos from the API. Replace the PUSHER_APP_* keys with the one from your Pusher dashboard.

mounted方法中,我们创建Pusher库的实例。 然后,我们在photo-stream频道上收听new-photo事件。 触发事件后,我们会将事件中的新照片添加到photos列表中。 我们还向/photos发送GET请求,以从API中获取所有照片。 将PUSHER_APP_*键替换为Pusher仪表板中的键。

In the methods property, we added a few methods. The filePicker is triggered when the ‘Upload’ button is pressed on the UI. It triggers a file picker that allows the user to upload photos. The upload method takes the uploaded file and sends a POST request with the file to the API for processing.

methods属性中,我们添加了一些方法。 在UI上按下“上传”按钮时,将触发filePicker 。 它触发一个文件选择器,允许用户上传照片。 upload方法获取上传的文件,并将带有该文件的POST请求发送到API进行处理。

That’s all for the front end. You can save the file and head over to your web browser. Visit http://127.0.0.1:9000 to see your application in action.

仅此而已。 您可以保存文件并转到Web浏览器。 访问http://127.0.0.1:9000以查看您的应用程序在运行。

Here’s how it will look again:

再次显示如下:

结论 (Conclusion)

In this article, we have been able to demonstrate how you can use Pusher Channels in your Go application to provide realtime features for your application.

在本文中,我们已经演示了如何在Go应用程序中使用Pusher Channels为应用程序提供实时功能。

As seen from the code samples above, it is very easy to get started with Pusher Channels. Check the documentation to see other ways you can use Pusher Channels to provide realtime features to your users.

从上面的代码示例可以看出,使用Pusher Channels非常容易入门。 查看文档,以了解使用推播频道向用户提供实时功能的其他方式。

The source code for this application is available on GitHub.

该应用程序的源代码可在GitHub上找到 。

This article was first published on Pusher.

本文最初在Pusher上发表。

翻译自: https://www.freecodecamp.org/news/how-to-build-a-photo-feed-with-go-and-vue-js-9d7f7f39c1b4/

vue.js 构建项目

你可能感兴趣的:(数据库,java,vue,web,python,ViewUI)