用Go+Vue.js快速搭建一个Web应用(初级demo)

2020-01-28 12:40:30丽君

新建templates目录,并目录下新建index.html,内容如下:


<html>
  <h1>
    {{ .title }}
  </h1>
</html>

新建一个group v2,并创建/index路由,返回静态html页面:


r.LoadHTMLGlob("templates/*")
v2 := r.Group("/v2")
{
  v2.GET("/index", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.html", gin.H{      "title": "hello Gin.",
    })
  })
}

使用LoadHTMLGlob定义模板文件路径,用c.HTML返回静态页面。访问:


curl -XGET 'http://127.0.0.1:8000/v2/index' -i
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Mon, 18 Sep 2017 08:29:13 GMT
Content-Length: 55
<html lang="en">
  hello Gin.
</html>

Gin返回了静态文件index.html,并把title数据填充到了模板 {{ .title }}

注:关于模板语言的使用,读者自行补充。当然静态资源我们也可以交由nginx等来处理,减少服务器压力。

Gin默认路由

我们还可以为Gin定义一些默认路由:


// 404 NotFound
r.NoRoute(func(c *gin.Context) {
       c.JSON(http.StatusNotFound, gin.H{
            "status": 404,  
            "error": "404, page not exists!",
       })
})

这时候,我们访问一个不存在的页面:


curl -XGET 'http://127.0.0.1:8000/v2/notfound' -i
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Mon, 18 Sep 2017 09:22:38 GMT
Content-Length: 46
{"error":"404, page not exists!","status":404}

Gin 中间件

在go的net/http中我们可以很方便的设计中间件,同样Gin也为我们提供了很方便的中间件使用。 我们可以定义全局中间件,群组中间件和单个路由的中间件,可以限定中间件的作用范围。

先定义一个简单的中间件,并将其设为全局中间件:


// PrintMiddleware is a function for test middleware
func PrintMiddleware(c *gin.Context) {
  fmt.Println("before request")
  c.Next()
}

接下来注册为全局中间件:


r := gin.Default()
r.Use(PrintMiddleware())

然后我们发起客户端请求并查看Gin控制台输出:


curl -XGET 'http://127.0.0.1:8000/v2/index' -i
[GIN-debug] Listening and serving HTTP on :8000
before request
[GIN] 2017/09/18 - 17:42:50 | 200 |   809.559µs |    127.0.0.1 | GET   
/v2/index

可以看到Gin在执行请求前,成功执行了自定义的中间件函数,c.Next()表示当中间件执行完成之后,将请求传递给下一个函数处理。

上面定义了一个全局中间件,现在我们想对v2组的请求进行一次验证(模拟登录),假设请求中包含一个token参数,存储认证信息,我们来实现这个中间件函数: