Ajax 提供多个静态文件并在golang中发出post请求
我两天前才开始使用Golang,所以这可能很简单,但对我来说很难。Ajax 提供多个静态文件并在golang中发出post请求,ajax,http,go,Ajax,Http,Go,我两天前才开始使用Golang,所以这可能很简单,但对我来说很难。 我问题的第一步是在目录“/static”下提供多个文件,我已经知道如何做了( ),但我也想发出POST请求(将信息保存到MongoDB数据库),这是困扰我的部分。有一个代码示例允许提供一个静态文件和一个POST请求,但我无法用自己的能力进行修改。此示例可在此处找到:https://www.golangprograms.com/example-to-handle-get-and-post-request-in-golang.htm
我问题的第一步是在目录“/static”下提供多个文件,我已经知道如何做了( ),但我也想发出POST请求(将信息保存到MongoDB数据库),这是困扰我的部分。有一个代码示例允许提供一个静态文件和一个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)
}
}
我问了第一个问题,你回答了第一个问题:)
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)
}
}