简体   繁体   English

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

[英]Serve multiple static files and make a post request in golang

I just started using Golang 2 days ago, so this is probably pretty simple, but nevertheless hard for me.我两天前才开始使用 Golang,所以这可能很简单,但对我来说却很难。
The first step of my question was to serve multiple files under the directory "/static", which I already know how to do (我的问题的第一步是在“/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)
  }
})

), but I want to make POST requests too (to save information to a MongoDB database) which is the part that stumps me. ),但我也想发出 POST 请求(将信息保存到 MongoDB 数据库),这是让我难过的部分。 There is a code sample that does allow to serve one static file and a POST request, but I couldn't modify with my abilities.有一个代码示例确实允许提供一个 static 文件和一个 POST 请求,但我无法用我的能力进行修改。 This sample can be found here:https://www.golangprograms.com/example-to-handle-get-and-post-request-in-golang.html.此示例可在此处找到:https://www.golangprograms.com/example-to-handle-get-and-post-request-in-golang.html。 Can I make it somehow to serve multiple static files (under the directory "static" preferably)?我可以以某种方式提供多个 static 文件(最好在“静态”目录下)吗?

Write a handler that calls through to fs for non-POST requests:编写一个处理程序,通过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
}

Use the handler like this:像这样使用处理程序:

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