大猩猩mux,不包括扩展请求

An attempt to configure go server routing with github.com/gorilla/mux to respond to all requests with index.html but exclude requests with extension .jpg|.js|.png

Static files excluded due to extension will be routed to FileServer. configured.

Failed Attempt

  func main() {
        r := mux.NewRouter()

        r.HandleFunc("/{path:^.*([!js|jpg|png|gif])$}", func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, "dist/index.html")
        })

        r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("dist"))))

        http.Handle("/", r)
        http.ListenAndServe(":8000", nil)
    }

This "^.*([!js|jpg|png|gif])$}" is not a valid regular expession for matching string that does not have .jpg|.js|.png

However, In golang Negative lookahead isn't supported for technical reasons, specifically because it conflicts with the O(n)-time guarantees of the library.

I would suggest you to do it other way around ie, add handlers for png,js,css files etc to serve the files as such

Better approach welcome, hoped to use regular expression so things where left intact with no crazy if/else conditions

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/{path:.*}", func(w http.ResponseWriter, r *http.Request) {
        if HasSuffix(r.URL.Path, []string{"js", "css", "gif", "jpeg", "woff2", "woff", "ttf"}) == false {
            fmt.Println("serving index")
            http.ServeFile(w, r, "dist/index.html")
        } else {
            http.ServeFile(w, r, "dist/"+r.URL.Path)
        }
    })

    //r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("dist"))))

    http.Handle("/", r)
    http.ListenAndServe(":8000", nil)
}

//HasSuffix check if url has suffix
func HasSuffix(path string, parts []string) bool {
    for _, part := range parts {
        fmt.Println("checking if part:" + part + " exists in path:" + path)
        if strings.HasSuffix(path, part) == true {
            return true
        }
    }
    return false
}