How to remove index.html path from url in golang

How can I remove index.html

from my url string eg.localhost:8000/index.html

package main

import (
    "net/http"
    "io/ioutil"
)

func main() {
    http.Handle("/", new(MyHandler))

    http.ListenAndServe(":8000", nil)
}
type MyHandler struct {
    http.Handler
}

func (this *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    path := "public" + req.URL.Path
    data, err := ioutil.ReadFile(string(path))

    if err == nil {
        w.Write(data)
    } else {
        w.WriteHeader(404)
        w.Write([]byte("404 - " + http.StatusText(404)))
    }
}

      

+3


source to share


1 answer


Add a condition to serve index.html if the URL path is empty:

path := "public"
if req.URL.Path == "/" {
    path += "/index.html"
} else {
    path += req.URL.Path
}

      



Also, it would be nice to use it net/http.ServeFile

to manually write data to the output stream (see net/http#ServeContent

to see why it's a good idea).

It's also worth noting that there is a built-in handler for serving files .

+2


source







All Articles