是的,您猜对了。标记为静态的文件/文件夹是与Go应用分开提供的(使用Google的内容传输网络),因此无法知道Go应用的会话ID和状态。
对您来说有问题吗?通常,静态文件(例如HTML,CSS和Javascript文件)可以在未经授权/身份验证的情况下交付,它们不会带来安全风险。
如果您不想让静态文件“公开”,则必须使用Go应用程序来提供这些文件。不要将它们标记为静态的,并且使用任何服务Go的标准库的机制的文件(例如
http.FileServer(),
http.ServeFile()或
http.ServeContent())。使用中间件模式检查会话是否存在,如果存在,则仅调用文件服务器。
(或自行实现提供静态内容的服务,您可以在自己的处理程序中做任何您想做/需要做的事情。)
例如,要将Go中的“受保护”文件映射到
/protected,并将某些“真实”静态文件(由Google自动提供)映射到
/static,则可能看起来像这样:
app.yaml:
- url: /protected/.* script: _go_app- url: /static static_dir: static
然后,您可以在Go来源中提供“受保护的”文件,如下所示:
func init() { fileHandler := http.StripPrefix("/protected", http.FileServer(http.Dir("protected"))) http.HandleFunc("/protected/", func(w http.ResponseWriter, r *http.Request) { // You may check if a session exists here sessExists := ... if !sessExists { http.Error(w, "you must login first", http.StatusUnauthorized) return } // Serve the requested file: fileHandler.ServeHTTP(w, r) })}上面的
init()函数注册了一个处理程序,该处理程序处理带有前缀的路径
/protected/,如果存在会话(该逻辑属于您),它将调用提供该
protected文件夹内容的文件服务器。所提供的文件是从路径派生而来的,
/protected前缀已去除。例如,路径
/protected/secret.txt将指定
protected/secret.txt文件。



