pigfox
pigfox

Reputation: 1401

Serving selected folders only

I have a Go static content website issue. My structure looks like this:

|-Go
|--static/*
|--go.mod
|--main.go

When I serve the static content this way

    router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        http.FileServer(http.Dir("./")).ServeHTTP(res, req)
    })

I can see the contents of go.mod in the url https://example.com/go.mod

Then I changed the code to

    router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        http.FileServer(http.Dir("./static/*")).ServeHTTP(res, req)
    })

I also tried

    router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
    })

I can no longer see the contents of go.mod in the url https://example.com/go.mod

But my logo is not visible anymore <img src="/static/imgs/logo.png" alt="logo" id="logo"/>

How can I only serve the contents of the ./static/ dir?

Upvotes: 1

Views: 26

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51572

To server content under static dir:

http.FileServer(http.Dir("./static/"))

The requests for /imgs/logo.png then will be server from ./static/imgs/logo.png, (not /static/img/logo.png)

If you want to also include /static/ in your URLs:

http.StripPrefix("/static/",http.FileServer(http.Dir("./static/")))

Upvotes: 1

Related Questions