安装
本指南将引导您完成安装过程。您可以使用 Goyave 模板项目快速启动项目(如下所述),也可以手动设置。
模板项目
Goyave 模板项目将帮助您在几秒钟内快速开始。它提供了完整的目录结构和脚手架,让您可以立即开始构建。它包含最简设置,因此您无需清理不需要的内容。
Linux / MacOS
sh
$ curl https://goyave.dev/install.sh | bash -s github.com/用户名/项目名提示
将 github.com/用户名/项目名 替换为您的模块名称。
Windows (Powershell)
powershell
> & ([scriptblock]::Create((curl "https://goyave.dev/install.ps1").Content)) -moduleName github.com/用户名/项目名提示
将 github.com/用户名/项目名 替换为您的模块名称。
在项目目录中运行 go run . 启动服务器。服务器应该会无错误启动。
但是,没有注册任何路由。您可以添加一个简单的 "hello world" 路由,如下所示:
go
// http/route/route.go
router.Get("/hello", func(response *goyave.Response, _ *goyave.Request) {
response.String(http.StatusOK, "Hello world")
})重新启动服务器,然后尝试请求 hello 路由。了解更多关于路由的信息请点击这里。
sh
$ curl http://localhost:8080/hello现在您的项目已经准备就绪,让我们开始通过配置来自定义它。
从零开始
如果您决定从零开始安装项目,例如如果您不打算使用框架的某些功能,或者想要使用不同的目录结构,您可以这样做!但是,请考虑遵循标准目录结构。
在终端中,将工作目录更改为项目根目录后运行以下命令:
sh
$ go mod init github.com/用户名/项目名
$ go get -u goyave.dev/goyave/v5提示
将 github.com/用户名/项目名 替换为您的模块名称。
现在您的项目目录已设置并且依赖项已安装,让我们从程序入口点 main.go 开始:
go
package main
import (
"fmt"
"os"
"github.com/用户名/项目名/http/route"
"goyave.dev/goyave/v5"
"goyave.dev/goyave/v5/util/errors"
)
func main() {
opts := goyave.Options{}
server, err := goyave.New(opts)
if err != nil {
fmt.Fprintln(os.Stderr, err.(*errors.Error).String())
os.Exit(1)
}
server.Logger.Info("注册钩子")
server.RegisterSignalHook()
server.RegisterStartupHook(func(s *goyave.Server) {
s.Logger.Info("服务器正在监听", "host", s.Host())
})
server.RegisterShutdownHook(func(s *goyave.Server) {
s.Logger.Info("服务器正在关闭")
})
server.Logger.Info("注册路由")
server.RegisterRoutes(route.Register)
if err := server.Start(); err != nil {
server.Logger.Error(err)
os.Exit(2)
}
}TIP
server.Start() 是阻塞的。它将在服务器关闭或启动失败时返回。
现在我们需要创建用于注册路由的包。创建新包 http/route 和 http/route/route.go:
go
package route
import (
"net/http"
"goyave.dev/goyave/v5"
"goyave.dev/goyave/v5/cors"
"goyave.dev/goyave/v5/middleware/parse"
"goyave.dev/template/http/controller/user"
)
func Register(_ *goyave.Server, router *goyave.Router) {
router.Get("/hello", func(response *goyave.Response, request *goyave.Request) {
response.String(http.StatusOK, "Hello world")
})
}这里我们注册了一个非常简单的显示 "Hello world" 的路由。了解更多关于路由的信息请点击这里。
最后,创建一个空的配置文件 config.json,包含一个空的 JSON 对象:{}。您可以在下一页找到有关配置的更多信息。
您可以运行服务器并请求您的路由:
sh
$ go run .在另一个终端中:
sh
$ curl http://localhost:8080/hello