Go-Spring 入门篇(一)

安装

# 拉取 go spring 核心包
$ go get github.com/go-spring/go-core@v1.1.0-rc2

# 如果需要使用 go-spring 做 web 服务
$ go get github.com/go-spring/starter-gin@v1.1.0-rc2

创建文件

package main

import (
    "log"

    "github.com/go-spring/spring-core/gs"
    "github.com/go-spring/spring-core/web"
    _ "github.com/go-spring/starter-gin"
)

func init() {
    gs.Object(new(Controller)).Init(func(c *Controller) {
        gs.GetMapping("/", c.Home)
    })
}

type Controller struct{}

func (c *Controller) Home(ctx web.Context) {
    ctx.String("Ok!")
}

func main() {
    log.Fatal(gs.Run())
}
  • 其中 init 方法里我们注册了一个 Controller 的空实例,这个不一定要在 init 中,可以在 gs.Run() 调用前的任意地方注册,使用 init 的原因是可以不依赖包内部方法,只需要导入即可注入。
  • 然后通过 Init 注册路由,gs.GetMapping 是容易封装的路由挂载器。
  • Home(ctx web.Context) 里边的 web.Context 则封装了请求和响应的操作。
  • github.com/go-spring/starter-gin 导入替换 github.com/go-spring/starter-echo 可以直接替换为 echo 框架。

启动程序

$ go run main.go
$ [INFO] github.com/go-spring/spring-core@v1.1.0-beta/gs/gs.go:296 container refreshed successfully
$ [INFO] github.com/go-spring/spring-core@v1.1.0-beta/gs/app.go:214 application started successfully
$ [INFO] github.com/go-spring/spring-core@v1.1.0-beta/web/container.go:169 [GET] :8080 / -> demo/go/filesystem/main.go:19 (*Controller).Home
$ [INFO] github.com/go-spring/spring-gin@v1.1.0-beta/container.go:121 ⇨ http server started on :8080

控制台输入 curl 127.0.0.1:8080 或浏览器访问,得到如下结果代表程序运行成功

$ curl http://127.0.0.1:8080
$ Ok!

官网及交流

Go-Spring 官网
Github

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!