3
votes

I'm trying to serve different HTML files depending on the route. The router works fine for "/" and it serves the index.html. However when going to any other route like "/download", it also renders the index.html, even tho the file that is to be served is called share.html.

What am I doing wrong here?

    package main

import (
    "net/http"
    "github.com/gorilla/mux"
    "log"
    "path"
    "fmt"
)

// main func
func main() {
    routes()
}

// routes
func routes() {
    // init router
    r := mux.NewRouter()
    // index route
    r.HandleFunc("/", home)
    r.HandleFunc("/share", share)
    r.HandleFunc("/download", download)

    // start server on port 1337
    log.Fatal(http.ListenAndServe(":1337", r))
}

// serves index file
func home(w http.ResponseWriter, r*http.Request) {
    p := path.Dir("./public/views/index.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

// get shared files
func share(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        if err := r.ParseForm(); err != nil {
            fmt.Fprint(w, "ParseForm() err: %v", err)
            return
        }
        log.Println(r.FormValue("name"))
        http.Redirect(w, r, "/download", http.StatusMovedPermanently)
    }
}

func download(w http.ResponseWriter, r *http.Request) {
    p := path.Dir("./public/views/share.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}
2
I don't actively see an error in the code, are you sure you restarted the GO process after making the change?Derek Pollard
Remove all calls to path.Dir(). This call returns the directory part of the path. The code serves index.html because ServeFile looks for index.html when given a directory.Cerise Limón
It works! Thanks alot ThunderCat.Sander Hellesø
you should directly use http.ServeFile(w, r, /* file or directory name */) to resolve ambiguityKMA Badshah

2 Answers

4
votes

I believe you might be looking for "PathPrefix"

func routes() {
    // init router
    r := mux.NewRouter()
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/views/")))
}
1
votes

Remove all calls to path.Dir(). This call returns the directory part of the path. The code serves index.html because ServeFile looks for index.html when given a directory.