繁体   English   中英

服务多个 static 文件并在 golang 中发出 post 请求

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM