Kudos
Kudos

Reputation: 51

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.
The first step of my question was to serve multiple files under the directory "/static", which I already know how to do (

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. 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. This sample can be found here: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)?

Upvotes: 2

Views: 1052

Answers (1)

volker
volker

Reputation: 36

Write a handler that calls through to fs for non-POST requests:

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)
    }
}

Upvotes: 2

Related Questions