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)
}
http.ServeFile(w, r, /* file or directory name */)
to resolve ambiguity – KMA Badshah