[英]Serve multiple static files and make a post request in golang
我兩天前才開始使用 Golang,所以這可能很簡單,但對我來說卻很難。
我的問題的第一步是在“/static”目錄下提供多個文件,我已經知道該怎么做(
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal(err)
}
})
),但我也想發出 POST 請求(將信息保存到 MongoDB 數據庫),這是讓我難過的部分。 有一個代碼示例確實允許提供一個 static 文件和一個 POST 請求,但我無法用我的能力進行修改。 此示例可在此處找到:https://www.golangprograms.com/example-to-handle-get-and-post-request-in-golang.html。 我可以以某種方式提供多個 static 文件(最好在“靜態”目錄下)嗎?
編寫一個處理程序,通過fs
調用非 POST 請求:
type handler struct {
next http.Handler
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
h.next.ServeHTTP(w, r)
return
}
// write post code here
}
像這樣使用處理程序:
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", handler{fs})
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal(err)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.