目录
go-zero微服务框架的静态文件服务
应用场景
通过 go-zero 的 rest.WithFileServer("/public", http.Dir("./static/html")) 来给 restful 服务增加文件服务能力。即开放公开目录给外部访问。
go-zero版本
go-zero v1.7.0
新建项目目录
mkdir demo
cd demo
新建 demo.api 文件
demo.api
写入内容- syntax = "v1"
- type Request {
- Name string `path:"name,options=you|me"`
- }
- type Response {
- Message string `json:"message"`
- }
- service demo-api {
- @handler DemoHandler
- get /from/:name (Request) returns (Response)
- }
- //goctl api go -api core.api -dir ./ -style go_zero
复制代码 生成api代码
goctl api go -api core.api -dir ./ -style go_zero
新建静态1.html文件
demo/static/html/1.html
写入内容
hello 1.html
检察文件目录
- .
- ├── demo.api
- ├── demo.go
- ├── etc
- │ └── demo-api.yaml
- ├── go.mod
- ├── go.sum
- ├── internal
- │ ├── config
- │ │ └── config.go
- │ ├── handler
- │ │ ├── demo_handler.go
- │ │ └── routes.go
- │ ├── logic
- │ │ └── demo_logic.go
- │ ├── svc
- │ │ └── service_context.go
- │ └── types
- │ └── types.go
- └── static
- └── html
- └── 1.html
复制代码 写入静态服务代码
修改demo.go- package main
- import (
- "flag"
- "fmt"
- "net/http"
- "demo/internal/config"
- "demo/internal/handler"
- "demo/internal/svc"
- "github.com/zeromicro/go-zero/core/conf"
- "github.com/zeromicro/go-zero/rest"
- )
- var configFile = flag.String("f", "etc/demo-api.yaml", "the config file")
- func main() {
- flag.Parse()
- var c config.Config
- conf.MustLoad(*configFile, &c)
- // 在 `./static/html` 目录下有需要对外提供的文件,比如有个文件 `1.html`,
- // 以 `http://127.0.0.1:8888/public/1.html` 这样的路径就可以访问该文件了。
- // public 在浏览器中访问的目录 映射到./static/html目录
- server := rest.MustNewServer(c.RestConf, rest.WithFileServer("/static", http.Dir("./static/html"))) #
- defer server.Stop()
- ctx := svc.NewServiceContext(c)
- handler.RegisterHandlers(server, ctx)
- fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
- server.Start()
- }
复制代码 启动api服务
go mod tidy
go run demo.go
访问1.html
- curl -XGET http://127.0.0.1:8888/public/1.html
- hello 1.html
复制代码
参考文档
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |