Quickly build a web application (primary demo) with go + vue.js

Time:2020-1-21

As one of the most popular front-end libraries, vue.js has a new thinking mode for rapid construction and development of front-end projects. This article introduces how to build a web application (primary demo) quickly with go + vue.js.

Environmental preparation:

1. Install go language and configure go development environment;

2. Install node.js and NPM environment;

Use of gin:

In order to quickly build back-end applications, gin is used as the web framework. Gin is a web framework implemented in golang. Its API is very friendly and has excellent routing performance and detailed error prompts. If you want to develop a high-performance production environment quickly, gin is a good choice.

Download and install gin:

go get github.com/gin-gonic/gin

Used in Code:


import "github.com/gin-gonic/gin"

Here is a simple example of using gin:


package main 
import "github.com/gin-gonic/gin" 
 func main() { 
  r := gin.Default() 
  r.GET("/ping", func(c *gin.Context) { 
    c.JSON(200, gin.H{ 
      "message": "pong", 
    }) 
  }) 
  r.Run() // listen and serve on 0.0.0.0:8080 
}

Note: Gin can easily support various HTTP request methods and return various types of data. For details, go to https://github.com/gin-epic/gin.

Start a project:

Create a new project in gogland (IDE): demo, and create a main.go file as the project entry:


package main 
import ( 
  "demo/router" 
) 
 func main() { 
  router.Init() // init router 
}

Note: package main in go must contain a main function.

As can be seen from the above code, we introduced the router package below demo and explicitly called the init() function of router. Now, we will create a new router directory under demo project and create router.go under the directory to write routing rules. The code is as follows:


package router
import (
     "demo/handlers"
     "github.com/gin-gonic/gin"
)
func Init() {
     // Creates a default gin router
     r := gin.Default()  // Grouping routes
     // group: v1
     v1 := r.Group("/v1")
     {
         v1.GET("/hello", handlers.HelloPage)
     }
     r.Run(":8000") // listen and serve on 0.0.0.0:8000
}

Here, we create a default route for gin, assign a group V1 to it, listen to Hello requests and route them to the view function hellopage, and finally bind to 0.0.0.0:8000.

Now let’s create a view function, create a new handlers directory, and create a hello.go file in the directory. The code is as follows:


package handlers 
import ( 
     "github.com/gin-gonic/gin" 
     "net/http" 
) 
func HelloPage(c *gin.Context) { 
     c.JSON(http.StatusOK, gin.H{ 
         "message": "welcome", 
     }) 
}

C. JSON is a built-in method for gin to return JSON data, which contains two parameters, status code and returned content. Http.statusok means that the return status code is 200 and the text is{"message": "welcome"}

Note: Gin also contains more return methods, such as c.string, c.html, c.xml, etc. please learn by yourself.

So far, we have implemented the most basic code for gin to build web services, running the code:


~/gofile/src/demo$ go run main.go
[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         --> demo/handlers.HelloPage (3 handlers)
[GIN-debug] Listening and serving HTTP on :8000

As you can see, we have successfully started the web server and listened to the local 8000 port. Now we can access the address of / V1 / Hello:


curl -XGET 'http://127.0.0.1:8000/v1/hello' -i
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8Date: Mon, 18 Sep 2017 07:38:01 GMT
Content-Length: 21
{"message":"welcome"}

Here, the server has correctly responded to the request and returned{"message":"welcome"}At the same time, it can be seen from the HTTP request header that the request status code is 200 and the returned data type is content type: application / JSON.

Let’s look at the output information of the server’s console:


[GIN] 2017/09/18 - 15:37:46 | 200 |   81.546µs |    127.0.0.1 | GET   /v1/hello

So far, we have successfully built a set of simple web servers. But in the real world, we will definitely generate data communication with the server. Next, let’s see how gin receives parameters.

Gin parameter usage

When restful is widely popular, gin can easily receive URL parameters:

We defined a new route under the previous group V1 route:


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

Next visit:


curl -XGET 'http://127.0.0.1:8000/v1/hello/lilei' -i
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Mon, 18 Sep 2017 08:03:02 GMT
Content-Length: 11
Hello lilei

As you can see, with the c.param (“key”) method, gin successfully captures the parameters in the URL request path. Gin can also receive general parameters as follows:


v1.GET("/welcome", func(c *gin.Context) {
  firstname := c.DefaultQuery("firstname", "Guest")
  lastname := c.Query("lastname")
  c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})

Similarly, we visit:


curl -XGET 'http://127.0.0.1:8000/v1/welcome?firstname=li&lastname=lei' -i
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8Date: Mon, 18 Sep 2017 08:11:37 GMT
Content-Length: 12
Hello li lei

adoptc.Query("key")The URL parameter can be received successfully. C.defaultquery will be replaced by its default value guest when the parameter does not exist.

Note: Gin can also receive more parameters of different types. Please check gin’s documentation;

Gin returns to static page

We will definitely involve the processing of static resources in website development. Here is a simple example of gin returning static pages and realizing data interaction.

Create a new templates directory, and create index.html under the directory, as follows:


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

Create a new group V2, and create a / index route to return to the static HTML page:


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.",
    })
  })
}

Use loadhtmlglobe to define the template file path and c.html to return to the static page. Visit:


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 returns the static file index.html and populates the title data into the template{{ .title }}

Note: for the use of template language, the reader shall supplement by himself. Of course, static resources can also be handled by nginx to reduce server pressure.

Gin default route

We can also define some default routes for gin:


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

At this time, we visit a page that does not exist:


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 Middleware

In go’s net / HTTP, we can easily design middleware, and gin also provides us with a very convenient use of middleware. We can define global middleware, group middleware and single routing middleware, which can limit the scope of middleware.

First, define a simple middleware and set it as a global middleware:


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

Next, register as global middleware:


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

Then we initiate the client request and view the gin console output:


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

It can be seen that gin successfully executed the customized middleware function before executing the request. C.next () indicates that after the execution of the middleware is completed, the request will be passed to the next function for processing.

A global middleware is defined above. Now we want to verify (simulate login) the request of V2 group. Suppose that the request contains a token parameter to store authentication information, we can implement this middleware function:


func ValidateToken() gin.HandlerFunc {
     return func(c *gin.Context) {
         token := c.Request.FormValue("token")
         if token == "" {
             c.JSON(401, gin.H{     
                  "message": "Token required",
             })
             c.Abort()      
             return
         }   
         if token != "accesstoken" {
             c.JSON(http.StatusOK, gin.H{ 
                  "message": "Invalid Token",
             })
             c.Abort()      
             return
    }
    c.Next()
  }
}

Then we register the middleware in group V2:


v2.Use(ValidateToken())

Next, we will visit as usual:


curl -XGET 'http://127.0.0.1:8000/v2/index' -i
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Date: Mon, 18 Sep 2017 10:01:10 GMT
Content-Length: 32
{"message":"Token required"}

Prompt us for token required. When we add token:


curl -XGET 'http://127.0.0.1:8000/v2/index?token=accesstoken' -i
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Mon, 18 Sep 2017 10:02:28 GMT
Content-Length: 29
<html>
  hello Gin.
</html>

As you can see, gin has passed the verification and responded to the request correctly. c. Abort () indicates that the request was terminated.

See here, I believe you have a general understanding of gin, and you can do your own code. In the actual development, there will be a variety of needs, at this time, we need to consult the data from many sides to find the answer.

Vue.js use

Vue.js is a popular front-end framework. We can use vue.js and gin to build front-end and back-end separate applications.

Official document of Vue: https://cn.vuejs.org/v2/guide/

Build Vue development environment:

1. Install node.js and NPM.

2. NPM installation Vue scaffold Vue cli:

NPM install Vue cli - g // global install

Vue cli is an official vue.js project scaffold, which can be used to create Vue projects quickly. GitHub address: https://github.com/vuejs/vue-cli

3. Next, use Vue cli to create a project, using the official web pack template:

vue init webpack demo

Here, the default setting can be used. Press enter all the way, and you will be prompted to complete the installation and enter the project

cd demo

Installation dependency (need to wait for a while):

npm install

4. Start the development server:

npm run dev

Visit: http: / / localhost: 8080, and you can see the initialization page set up by Vue official for us.

Here, we have set up the initial project template of Vue conveniently, so how can we realize the data interaction work of front and back end separation? Next, use a recently used small case to demonstrate data interaction.

Draw a simple chart using echarts

1. Create a new views directory under SRC directory to store views (directory structure):


src
├── App.vue
├── assets
│  └── logo.png
├── components
│  └── HelloWorld.vue
├── main.js
├── router
│  └── index.js
└── views
  ├── ChartLine.vue
  └── index.js

2. Install the components that will be used later:

npm install echarts --save-dev // echarts
NPM install Axios -- save dev // an asynchronous HTTP request Library

3. Create a new chartline.vue file to display the line chart. The contents are as follows:

<template>
 <div>
  <div>
   < button v-on: Click = "refreshcharts()" > refresh < / button >
   <div></div>
  </div>
 </div>
</template>
<script>
 import echarts from 'echarts'
 import axios from 'axios'
 export default {
  name: 'ChartLine',
  computed: {
   Opt() {// option can refer to the official case of echarts
    return {
     title: {
      Text: 'stacking area map'
     },
     tooltip: {
      //Omitted. See the official case of echarts for parameters
     },
     legend: {
      Data: ['email marketing']
     },
     grid: {
      // ellipsis
     },
     xAxis: [
      {
       // ellipsis
       data: []
      }
     ],
     yAxis: [
      // ellipsis
     ],
     series: [
      {
       Name: 'email marketing',
       type: 'line',
       data: []
      }
     ]
    }
   }
  },
  methods: {
   async refreshCharts () {
    const res = await axios.get('http://127.0.0.1:8000/api/v1/line')
    This. Mychart. Setoption ({// update data
     xAxis: {
      data: res.data.legend_data
     },
     series: {
      data: res.data.xAxis_data
     }
    })
   }
  },
  mounted () {
   this.myChart = echarts.init(document.getElementById('line'))
   This. Mychart. Setoption (this. OPT) // initialize echarts
   Window. Addeventlistener ('resize ', this. Mychart. Resize) // adaptive
  }
 }
</script>
<style>
.line {
 width: 400px;
 height: 200px;
 margin: 20px auto;
}
</style>

The above code implements the initialization and data filling process of echarts chart, as well as the function of clicking the button to refresh the chart;

4. Register route and edit router / index.js:


import Vue from 'vue'
import Router from 'vue-router'
import ChartLine from '../views/ChartLine.vue'
Vue.use(Router)
export default new Router({
 mode: 'history',
 routes: [
  {
   path: '/line',
   name: 'Line',
   component: ChartLine
  }
 ]
})

5. Implementation of gin background API interface:

v1.GET("/line", func(c *gin.Context) {
  Legenddata: = [] string {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
  xAxisData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
  c.JSON(200, gin.H{  
       "legend_data": legendData, 
       "xAxis_data": xAxisData,
  })
})

6. Now we can see the chart correctly. Click the refresh button to see that the chart has refreshed the data correctly.

summary

The above is a quick build of a web application (primary demo) with go + vue.js introduced by Xiaobian. I hope it can help you. If you have any questions, please leave a message to me and Xiaobian will reply to you in time. Thank you very much for your support of the developepaer website!

Recommended Today

JavaScript animation example: rotated equilateral triangle

Given that the coordinates of the center of gravity of an equilateral triangle are (x0, Y0) and the height is h, you can draw an equilateral triangle with horizontal bottom edge with the following statement.          ctx.beginPath();          ctx.moveTo(x0,y0-h*2/3);          ctx.lineTo(x0+h/Math.sqrt(3), y0+h/3);           ctx.lineTo(x0-h/Math.sqrt(3), y0+h/3);          ctx.lineTo(x0,y0-h*2/3);          ctx.closePath();          ctx.stroke(); Given the number of […]