Sander Hellesø
Sander Hellesø

Reputation: 271

Serve static html files with gorilla mux

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

Upvotes: 4

Views: 6260

Answers (2)

George Albertyn
George Albertyn

Reputation: 277

I believe you might be looking for "PathPrefix"

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

Upvotes: 5

Thundercat
Thundercat

Reputation: 120951

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.

Upvotes: 1

Related Questions