背景: 以前使用Golang的Gin框架进行一些运维内部后端的API接口开发,对外提供提供
json
类型的数据响应,可是该种方式在浏览器访问数据时数据格式不友好(因为是API接口,通常须要使用postman之类的工具来验证接口返回数据),后来尝试了使用Golang的template
模板来结合html进行数据渲染,但也发现比较缺少美感。以后决定使用前端框架来渲染后端数据,因为vue框架的各类优点,好比简单、数据的双向绑定等等好处,决定使用vue框架来开启个人前端之旅。接下来简单来说解下使用Golang后端和vue前端进行融合的示例。css
编写基于Gin框架的API:html
# 查看源码文件
$ 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-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
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项目的源码部分由这么几个部分组成node
main.js
App.vue
assets
components
router
咱们首先来看一下App.vue
代码python
# 咱们能够看到在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
文件:webpack
# 其实就是咱们刚才看到的欢迎页下面的一些超连接
$ 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
下的定义。ios
# 其实就是定义咱们如何能访问到这个资源
$ 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
}
]
})复制代码
如今咱们知道vue是如何渲染的相关数据,而且知道了大概的编码规则,可是咱们的数据并不在本地,而是一个对外API,此时咱们须要想办法让vue获取到后端的数据。git
没错,这个时候,咱们须要一些异步请求的方式让vue拿到数据,好比ajax
之类的,不过在大前端时代,有更好的工具,即axios
,接下来在咱们的vue环境中安装axios
环境:github
# 安装异步请求包
$ cnpm install --save axios复制代码
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>复制代码
# 增长路由
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
项目的融合。接下来就须要根据需求继续改造了。欢迎关注个人公众号