目录

  • go-zero微服务框架的静态文件服务
  • 应用场景
  • go-zero版本
  • 新建项目目录
  • 新建 demo.api 文件
  • 生成api代码
  • 新建静态1.html文件
  • 查看文件目录
  • 写入静态服务代码
  • 启动api服务
  • 访问1.html
  • 参考文档

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

go-zero微服务框架的静态文件服务_github

参考文档

[Haima的博客]