CTFm 开发日志 2020.6.19


emmmm 考虑很久决定把后端换成Gin,据说Go要比python快的多的多

go mod init ctfm_backend

但是Go的依赖由于某些不可抗力导致下载不了

修改为goproxy.io

go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.io,direct

安装完依赖后就可以用

go run main.go跑起来了

大致流程就是在生成环境下,frontend编译生成静态文件,然后放到backend去调用,api在backend实现,前端后端通过axios通信

写了一个简单的测试

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("/test", func(c *gin.Context) {
            // 注意:在前后端分离过程中,需要注意跨域问题,因此需要设置请求头
            c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
            testData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
            c.JSON(200, gin.H{
                "testData": testData,
            })
        })
    }
    //定义默认路由
    r.LoadHTMLGlob("../dist/*.html")        // 添加入口index.html
    r.LoadHTMLFiles("../dist/static/*/*")   // 添加资源路径
    r.Static("/static", "../dist/static")   // 添加资源路径
    r.StaticFile("/", "../dist/index.html") //前端接口

    r.NoRoute(func(c *gin.Context) {
        c.JSON(http.StatusNotFound, gin.H{
            "status": 404,
            "error":  "404, page not exists!",
        })
    })
    r.Run(":8633")
}
<!--
 * @Author: Eki
 * @Date: 2020-06-19 17:58:30
 * @LastEditTime: 2020-06-19 18:10:42
 * @LastEditors: Eki
 * @Description: Frontend Login Page
 * @FilePath: /CTFm/frontend/src/views/Login.vue
-->
<template>
  <div class="login">
    "Here Are Login!"
    {{testData}}
  </div>
</template>

<script>
// @ is an alias to /src
import Banner from '@/components/Banner.vue'
import axios from 'axios'

export default {
  name: 'login',
  components: {
    Banner
  },
  data () {
    return {
      testData: null
    }
  },
  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:8633/v1/test').then(response => (this.testData = response.data.testData))
  }
}
</script>

<style lang="scss">
.login {
  margin: 200px;
}
</style>

最终效果如下

image-20200619181404418.png

声明:Eki's Blog|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - CTFm 开发日志 2020.6.19


A Dreamer Full of Dream