使用Golang的Gin框架和vue编写web应用

2019年9月10日 239点热度 0人点赞 0条评论


背景: 之前使用Golang的Gin框架进行一些运维内部后端的API接口开发,对外提供提供json类型的数据响应,但是该种方式在浏览器访问数据时数据格式不友好(由于是API接口,一般需要使用postman之类的工具来验证接口返回数据),后来尝试了使用Golang的template模板来结合html进行数据渲染,但也发现比较缺乏美感。之后决定使用前端框架来渲染后端数据,由于vue框架的各种优势,比如简单、数据的双向绑定等等好处,决定使用vue框架来开启我的前端之旅。接下来简单来讲解下使用Golang后端和vue前端进行融合的示例。

基于Gin框架的后端API

编写基于Gin框架的API:

# 查看源码文件
$ cat main.go
/**
* @File Name: main.go
* @Author: xxbandy @http://xxbandy.github.io
* @Email:
* @Create Date: 2018-12-02 22:12:59
* @Last Modified: 2018-12-02 22:12:52
* @Description:
*/

package main

import (
_ "fmt"
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
)

func HelloPage(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "welcome to bgops,please visit https://xxbandy.github.io!",
})
}

func main() {
r := gin.Default()
v1 := r.Group("/v1")
{
v1.GET("/hello", HelloPage)
v1.GET("/hello/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})

v1.GET("/line", func(c *gin.Context) {
// 注意:在前后端分离过程中,需要注意跨域问题,因此需要设置请求头
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
legendData := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
xAxisData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
c.JSON(200, gin.H{
"legend_data": legendData,
"xAxis_data": xAxisData,
})
})
}
//定义默认路由
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"status": 404,
"error": "404, page not exists!",
})
})
r.Run(":8000")
}

# 运行程序
$ go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET /v1/hello --> main.HelloPage (3 handlers)
[GIN-debug] GET /v1/hello/:name --> main.main.func1 (3 handlers)
[GIN-debug] GET /v1/line --> main.main.func2 (3 handlers)

# 测试相关的接口
$ curl -s localhost:8000/v1/hello | python -m json.tool
{
"message": "welcome to bgops,please visit https://xxbandy.github.io!"
}

$ curl -s localhost:8000/v1/hello/bgops
Hello bgops

$ curl -s localhost:8000/v1/line
{"legend_data":["周一","周二","周三","周四","周五","周六","周日"],"xAxis_data":[120,240,81,387,150,230,180]}

# 可以看到该接口会返回一个json结构的数据
$ curl -s localhost:8000/v1/line | python -m json.tool
{
"legend_data": [
"\u5468\u4e00",
"\u5468\u4e8c",
"\u5468\u4e09",
"\u5468\u56db",
"\u5468\u4e94",
"\u5468\u516d",
"\u5468\u65e5"
],
"xAxis_data": [
120,
240,
347,
59,
150,
230,
180
]
}

基于vue框架的前端项目

使用vue-cli脚手架快速构建一个vue项目。
注意:前提是需要node环境,并且有可用的npm源

# 查看版本
$ npm -v
2.3.0

#升级 npm
cnpm install npm -g

# 升级或安装 cnpm
npm install cnpm -g

# 最新稳定版
$ cnpm install vue

# 全局安装 vue-cli
$ cnpm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
➜ vue-doc vue init webpack vue-test

? Target directory exists. Continue? Yes
? Project name vue-test
? Project description A Vue.js project
? Author xxbandy
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner jest
? Setup e2e tests with Nightwatch? Yes
//提供了两种方式[npm和yarn,如果默认选择npm时会去外网下载资源,可能无法访问谷歌外网]
? Should we run `npm install` for you after the project has been created? (recommended) no

vue-cli · Generated "vue-test".

# Project initialization finished!
# ========================

To get started:

cd vue-test
npm install (or if using yarn: yarn)
npm run lint -- --fix (or for yarn: yarn run lint --fix)
npm run dev

Documentation can be found at https://vuejs-templates.github.io/webpack

$ cd vue-test
$ cnpm install
✔ Installed 58 packages
✔ Linked 0 latest versions
✔ Run 0 scripts
All packages installed (used 237ms(network 227ms), speed 0B/s, json 0(0B), tarball 0B)

# run的时候会根据配置进行webpack静态资源编译
$ cnpm run dev
DONE Compiled successfully in 4388ms

> Listening at http://localhost:8080

当使用了cnpm run dev后,即成功运行起来一个前端服务,因此你会看到类似下面的页面。
图片

vue渲染后端API数据

1. 首先快速看一下vue项目的代码结构.

$ tree -L 1 .
.
├── README.md
├── build
├── config
├── index.html
├── node_modules
├── package.json
├── src
├── static
└── test
# 对于快速开发而言,只需要知道src目录下为vue相关的代码,即我们看到vue的欢迎页面就是src下的

$ tree -L 2 src
src
├── App.vue
├── assets
│ └── logo.png
├── components
│ └── HelloWorld.vue
├── main.js
└── router
└── index.js

注意: 可以看到一个vue项目的源码部分由这么几个部分组成

  • js主文件main.js

  • vue主文件App.vue

  • 静态文件目录assets

  • 自定义组件components

  • 路由目录router

我们首先来看一下App.vue代码

# 我们可以看到在div 这里有个img标签,这里其实就是我们刚才看到欢迎页面的vue的logo
# 其实可以看到使用了<router-view>标签,这里其实是定义了默认的组件,也就是下面导入的HelloWorld
$ cat App.vue
<!--展示模板-->
<template>
<!--这里用的是id选择器来绑定css样式的-->
<div id="app">
<img src="./assets/logo.png">
<router-view></router-view>
</div>
</template>

<script>
import HelloWorld from './components/HelloWorld'
export default {
name: 'helloworld',
components: {
HelloWorld
}
}
</script>
<!--样式代码-->
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

我们再来查看一下components/HelloWorld.vue文件:

# 其实就是我们刚才看到的欢迎页下面的一些超链接
$ cat components/HelloWorld.vue
<template>
<div class="HelloWorld">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<ul>
<li>
<a
href="https://vuejs.org"
target="_blank"
>

Core Docs
</a>
</li>
<li>
<a
href="https://forum.vuejs.org"
target="_blank"
>

Forum
</a>
</li>
<li>
<a
href="https://chat.vuejs.org"
target="_blank"
>

Community Chat
</a>
</li>
<li>
<a
href="https://twitter.com/vuejs"
target="_blank"
>

Twitter
</a>
</li>

.........

其实到这里,我们基本就知道了整个vue项目是如何把资源渲染出来的。不过我们再来看一下router下的定义。

# 其实就是定义我们如何能访问到这个资源
$ cat router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)

export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})

2. 思考我们接下来要做什么

现在我们知道vue是如何渲染的相关数据,并且知道了大概的编码规则,但是我们的数据并不在本地,而是一个对外API,此时我们需要想办法让vue获取到后端的数据。

没错,这个时候,我们需要一些异步请求的方式让vue拿到数据,比如ajax之类的,不过在大前端时代,有更好的工具,即axios,接下来在我们的vue环境中安装axios环境:

# 安装异步请求包
$ cnpm install --save axios

3. vue渲染后端数据

模拟编写一个components/HelloWorld组件

# 编写一个ApiData.vue的组件
$ cat components/ApiData.vue
<template>
<!--使用class来绑定css的样式文件-->
<div class="hello">
<!--{{}} 输出对象属性和函数返回值-->
<h1>{{ msg }}</h1>
<h1>site : {{site}}</h1>
<h1>url : {{url}}</h1>
<h3>{{details()}}</h3>
<h1 v-for="data in ydata" :key="data">{{data}}</h1>
<h3 v-for="item in xdata" :key="item">{{item}}</h3>
</div>
</template>

<script>
import axios from 'axios'
export default {
name: 'apidata',
// data用来定义返回数据的属性
data () {
return {
msg: 'hello,xxbandy!',
site: "bgops",
url: "https://xxbandy.github.io",
xdata: null,
ydata: null,
}
},
// 用于定义js的方法
methods: {
details: function() {
return this.site
},
},
mounted () {
// response返回一个json{"data": "数据","status": "状态码","statusText":"状态文本","headers":{ "content-type": "application/json; charset=utf-8" },"config":"配置文件","method":"方法","url":"请求url","request":"请求体"}
axios.get('http://localhost:8000/v1/line').then(response => (this.xdata = response.data.legend_data,this.ydata = response.data.xAxis_data))

}
}
</script>

<!--使用css的class选择器[多重样式的生效优先级]-->
<style>
.hello {
font-weight: normal;
text-align:center;
font-size:8pt;
}
h3
{
text-align:center;
font-size:20pt;
color:red;
}
</style>

在路由中增加我们的components

# 增加路由
cat router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
// 增加我们自定义的ApiData组件
import Hello from '@/components/ApiData'
Vue.use(Router)

export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
// 在这里引用我们的组件
{
path: '/xxb',
name: 'Hello',
component: Hello
}
]
})

App.vue文件中定义我们的vue脚本

# 增加如下内容
<script>
import Hello from './components/ApiData'
export default {
name: 'xxb',
components: {
Hello
}
}
</script>

运行服务

此时,我们可以运行服务,来检测我们的程序。

# 在vue的项目家目录下运行(由于我们的golang的api接口运行的是8000端口,因此vue的端口需要修改一下)
$ cnpm run dev
Your application is running here: http://localhost:8082

图片

图片

此时,我们就可以看到vue成功将后端Golang的API数据进行渲染出来了。虽然只是简单渲染,但,基本上已经实现了后端API和前端vue项目的融合。接下来就需要根据需求继续改造了。


欢迎关注我的公众号图片

13050使用Golang的Gin框架和vue编写web应用

root

这个人很懒,什么都没留下

文章评论