当我刚开始使用 Go 编程时,我发现它很难理解,感觉它比我以前学的其他语言都更底层。学了几个月之后,我变成 Go 语言的忠粉,并用它开发许多项目。
在本文中,我会分享如何使用 Go 和 Vue 搭建全栈 Web 应用程序。
我们要搭建什么项目
我觉得搭建一个网站缩略图生成器会很酷,就是当你输入一个网站 URL,应用程序将生成该网站的缩略图。
配置 Go 模块
首先,创建一个新的目录。然后,通过运行以下命令来配置 Go 模块。
go mod init github.com/Dirk94/website-thumbnail-generator
这样就创建了一个 go.mod
文件,包含模块的所有依赖。这和 node 项目中的 package.json
文件类似。
接下来,创建一个新的目录 main
,在里面增加一个 server.go
文件。这是应用程序的主入口。
现在,我们打印一行 “hello world”。
package main
import "fmt"
func main() {
fmt.Println("Hello world")
}
从项目目录运行以下命令,运行该程序:
go run main/server.go
Hello world
太好了,到目前为止一切正常!
配置 web 服务器
我们应该创建一个 web 服务器来监听传入的请求。
更新 main 函数:
func main() {
http.HandleFunc("/", homePageHandler)
fmt.Println("Server listening on port 3000")
log.Panic(
http.ListenAndServe(":3000", nil),
)
}
这将启动 web 服务器并监听端口 3000。
homePageHandler
函数将处理所有传入的请求。
func homePageHandler(w http.ResponseWriter, r *http.Request) {
_, err := fmt.Fprintf(w, "hello world")
checkError(err)
}
func checkError(err error) {
if err != nil {
log.Panic(err)
}
}
这个函数做的事情就是把 “hello world” 写入 http.ResponseWriter
。
checkError
函数的作用是在出现 error
的时候停止程序并打印堆栈跟踪。
运行该程序时,web 服务器将正确打印 “hello world” 消息!
创建 Vue 项目
从项目目录运行以下命令,创建一个新的 Vue 项目。
vue create frontend
这会创建很多文件,但是没关系,我们先运行 Vue 服务器。
yarn serve
访问 localhost:8081,可以看到 Vue app 了!
接下来,我们清理一下前端目录。
删掉 assets
和 components
,因为我们不需要它们。
然后更新 App.vue
文件。
<template>
<div id="app" class="container">
<div class="row">
<div class="col-md-6 offset-md-3 py-5">
<h1>Generate a thumbnail of a websiteh1>
<form v-on:submit.prevent="makeWebsiteThumbnail">
<div class="form-group">
<input v-model="websiteUrl" type="text" id="website-input" placeholder="Enter a website" class="form-control">
div>
<div class="form-group">
<button class="btn btn-primary">Generate!button>
div>
form>
div>
div>
div>
template>
使用 v-model
标签,在表单提交时调用 makeWebsiteThumbnail
函数。