Serve homepage and static content from root

前端 未结 3 612
臣服心动
臣服心动 2020-12-02 07:07

In Golang, how do I serve static content out of the root directory while still having a root directory handler for serving the homepage.

Use the following simple web

3条回答
  •  -上瘾入骨i
    2020-12-02 07:46

    One thing I thought of that might help you is that you can create your own ServeMux. I added to your example so that chttp is a ServeMux that you can have serve static files. The HomeHandler then checks to see if it should serve a file or not. I just check for a "." but you could do a lot of things. Just an idea, might not be what you are looking for.

    package main
    
    import (
        "fmt"
        "net/http"
        "strings"
    )   
    
    var chttp = http.NewServeMux()
    
    func main() {
    
        chttp.Handle("/", http.FileServer(http.Dir("./")))
    
        http.HandleFunc("/", HomeHandler) // homepage
        http.ListenAndServe(":8080", nil)
    }   
    
    func HomeHandler(w http.ResponseWriter, r *http.Request) {
    
        if (strings.Contains(r.URL.Path, ".")) {
            chttp.ServeHTTP(w, r)
        } else {
            fmt.Fprintf(w, "HomeHandler")
        }   
    } 
    

提交回复
热议问题