【发布时间】:2020-12-09 12:30:58
【问题描述】:
我的场景
编译后的 Angular 项目保存方式如下
.
├── branch1
│ ├── commitC
│ │ ├── app1
│ │ │ ├── index.html
│ │ │ └── stylesheet.css
│ └── commitD
│ ├── app1
│ │ ├── index.html
│ │ └── stylesheet.css
│ └── app2
│ ├── index.html
│ └── stylesheet.css
├── branch2
│ ├── commitE
│ ├── app1
│ │ ├── index.html
│ │ └── stylesheet.css
│ └── app2
│ ├── index.html
│ └── stylesheet.css
└── master
├── commitA
│ ├── app1
│ │ ├── index.html
│ │ └── stylesheet.css
└── commitB
├── app1
├── index.html
└── stylesheet.css
数据库
TABLE data(id , branch, commit)
条目:例如
| id | branch | commit |
|---|---|---|
| abc | branch1 | commitC |
| def | branch1 | commitD |
| ghi | master | commitA |
现在我想访问
:8080/apps/{id}
例如:localhost:8080/apps/abc
路径应该会在请求 DB 条目后生成
并且文件服务器为目录提供服务 ./files/branch1/commitC/
现在我希望看到文件夹 app1 和 app2
我有什么
func main() {
mux = mux.NewRouter()
mux.HandleFunc("/apps/{id}/{app}", s.serveApp).Methods("GET")
}
func (s *Server) serveApp(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
app := params["app"]
id := params["id"]
entry, err := getFromDB(id)
if err != nil {
w.Header().Set("Content-Type", "text/html")
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
file := filepath.Join(DefaultFolder, entry.Branch, entry.Commit, app, "index.html")
fmt.Printf("redirecting to %s", file)
http.ServeFile(w, r, file)
}
我怎样才能像这样服务整个目录,以便可以正确访问所有 css 和 js 文件?
我想我需要这样的东西
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
但是如何访问 mux.Vars(request) 来构建目录路径?
############ 关于 CSS 服务问题
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
mux := mux.NewRouter()
fs := http.FileServer(http.Dir("static"))
mux.Handle("/", fs)
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
CSS 文件以“文本/纯文本”形式提供
文件:
- main.go
- 静态/
- index.html
- main.css
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>A static page</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1>Hello from a static page</h1>
</body>
</html>
main.css
body {color: #c0392b}
【问题讨论】: