• beego 快速入门


    原文链接:https://beego.me/quickstart

    1.安装依赖

    git clone http://github.com/astaxie/beego.git
    git clone http://github.com/beego/bee.git
    
    cd bee/
    go build -o bee main.go 
    cp bee /usr/bin

    2.生成源码框架

    cd $GOPATH/src/
    bee new hello
    cd hello/
    go build main.go

    这时候运行main二进制,web可以直接访问8080端口

    简单示例

    下面这个示例程序将会在浏览器中打印 “Hello world”,以此说明使用 beego 构建 Web 应用程序是多么的简单!

    package main
    
    import (
        "github.com/astaxie/beego"
    )
    
    type MainController struct {
        beego.Controller
    }
    
    func (this *MainController) Get() {
        this.Ctx.WriteString("hello world")
    }
    
    func main() {
        beego.Router("/", &MainController{})
        beego.Run()
    }

    编译运行:

    $ go build -o hello hello.go
    $ ./hello

    这个时候你可以打开你的浏览器,通过这个地址浏览 http://127.0.0.1:8080 返回 “hello world”

    那么上面的代码到底做了些什么呢?

    1. 首先我们导入了包 github.com/astaxie/beego。我们知道 Go 语言里面被导入的包会按照深度优先的顺序去执行导入包的初始化(变量和 init 函数,更多详情),beego 包中会初始化一个 BeeAPP 的应用和一些参数。
    2. 定义 Controller,这里我们定义了一个 struct 为 MainController,充分利用了 Go 语言的组合的概念,匿名包含了 beego.Controller,这样我们的 MainController 就拥有了 beego.Controller 的所有方法。
    3. 定义 RESTful 方法,通过匿名组合之后,其实目前的 MainController 已经拥有了 GetPostDeletePut 等方法,这些方法是分别用来对应用户请求的 Method 函数,如果用户发起的是 POST 请求,那么就执行 Post 函数。所以这里我们定义了 MainController 的 Get 方法用来重写继承的 Get 函数,这样当用户发起 GET 请求的时候就会执行该函数。
    4. 定义 main 函数,所有的 Go 应用程序和 C 语言一样都是 main 函数作为入口,所以我们这里定义了我们应用的入口。
    5. Router 注册路由,路由就是告诉 beego,当用户来请求的时候,该如何去调用相应的 Controller,这里我们注册了请求 / 的时候,请求到 MainController。这里我们需要知道,Router 函数的两个参数函数,第一个是路径,第二个是 Controller 的指针。
    6. Run 应用,最后一步就是把在步骤 1 中初始化的 BeeApp 开启起来,其实就是内部监听了 8080 端口:Go 默认情况会监听你本机所有的 IP 上面的 8080 端口。
    • beego快速入门: https://beego.me/quickstart, 按照beego官方例子,先跑个hello world出来,哈哈!
    • beego开发文档: https://beego.me/docs/intro/, 开发文档过一遍
    • beego深入进阶: https://beego.me/products, beego官方列举的比较优秀的beego项目,通过阅读代码,学习别人的技巧
  • 相关阅读:
    Leetcode
    287. Find the Duplicate Number hard
    House Robber III leetcode 动态规划
    将一个数组分成奇数部分和偶数部分,并分别排好序 CVTE
    First Missing Positive && missing number
    permutation II (boss出来了)
    46. Permutations 回溯算法
    字符串分割 函数实现
    Combination Sum II Combinations
    用双缓存技术优化listview异步加载网络图片
  • 原文地址:https://www.cnblogs.com/wangjq19920210/p/11550777.html
Copyright © 2020-2023  润新知