File Server

How to provide file services using go-zero?

You can add file service capabilities to a restful service through go-zero using rest.WithFileServer(path, dir).

Here is an example code:

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/zeromicro/go-zero/rest"
  5. )
  6. func main() {
  7. // There are files in the `html` directory that need to be provided externally,
  8. // for example, a file named `index.html`, which can be accessed via the path `/static/index.html`.
  9. server := rest.MustNewServer(rest.RestConf{
  10. Host: "localhost",
  11. Port: 4000,
  12. }, rest.WithFileServer("/static", http.Dir("html")))
  13. defer server.Stop()
  14. server.AddRoute(rest.Route{
  15. Method: http.MethodGet,
  16. Path: "/hello",
  17. Handler: helloHandler,
  18. })
  19. server.Start()
  20. }
  21. func helloHandler(w http.ResponseWriter, r *http.Request) {
  22. w.WriteHeader(http.StatusOK)
  23. w.Write([]byte("Hello, World!"))
  24. }

This is just an example and generally should not be used for production services. It may be considered when the production service is very simple, but it is not best practice. Typically, file serving would be handled by nginx or cloud storage.

go-zero version: >= v1.7.0