google-app-engine - 静态页面在 Google App Engine 中返回 404

标签 google-app-engine go

我一直在使用 Golang 测试 Google App Engine SDK,但在提供静态 html 页面时遇到问题。如果我将内容添加到处理程序下的 app.yaml 中,那很好,但是当我尝试从我的 Go 应用程序内部路由它时;尝试 url http://localhost:8080/tr 页面返回 404。

我的文件系统设置为:

/main.go
/app.yaml
/testRoute.html

我的主要 app.go 看起来像这样:

import (
    "fmt"
    "net/http"
    "github.com/gorilla/mux"
)

func init() {
    r := mux.NewRouter()
    r.HandleFunc("/", index)
    r.HandleFunc("/tr", testRoute)
    http.Handle("/", r)
}

func index(w http.ResponseWriter, r *http.Request) {
   //No Issues here 
   fmt.Fprint(w, "Main Index.")
}

func testRoute(w http.ResponseWriter, r *http.Request) { 
    http.FileServer(http.Dir("testRoute.html")).ServeHTTP(w, r)
}

最佳答案

您不应该使用 Go 处理程序来提供静态文件(除非您想合并其他逻辑,例如高级日志记录或计数)。

您可以在应用的配置文件 app.yaml 中定义静态文件处理程序。这在官方文档中有详细说明:Static file handlers

Static files are files to be served directly to the user for a given URL, such as images, CSS stylesheets, or JavaScript source files. Static file handlers describe which files in the application directory are static files, and which URLs serve them.

For efficiency, App Engine stores and serves static files separately from application files. Static files are not available in the application's file system by default. This can be changed by setting the application_readable option to true.

Static file handlers can be defined in two ways: as a directory structure of static files that maps to a URL path, or as a pattern that maps URLs to specific files.

要使 AppEngine 自动提供静态文件,请将此条目添加到您的 app.yaml:

- url: /tr
  static_files: testRoute.html
  upload: testRoute.html

要使整个静态文件目录(包括递归的子文件夹)自动提供,请将此条目添加到 app.yaml:

- url: /assets
  static_dir: assets

关于google-app-engine - 静态页面在 Google App Engine 中返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638518/

相关文章:

python - 多个查询与手动排序一个大型查询 (AppEngine NDB)

go - 将较高类型向下转换为较低类型

go - 结构内的结构 slice/数组

amazon-web-services - 去 AWS 测试无效登录

go - 在有向图 Golang 中查找所有循环

python - 在 google app engine 上使用 python [xmlrpc frontend] 模块连接到 WordPress 博客

google-app-engine - Google App Engine 上的 Jython 开发

python - 什么时候可以在 Google App Engine 中抛出 DeadlineExceededError 异常

google-app-engine - 具有 GRPC 和 Cloud Endpoints 的 App Engine Flex 环境

go - 如何减少嵌套函数调用中的参数数量