-3

I need to set a cookie while serving static content, html, css & js.

The code below serves a naked html file, no css etc.

All the css & js live inside an "assets" folder on the same level as index.html.

Any suggestions?

func indexHandler(w http.ResponseWriter, req *http.Request) {
    http.SetCookie(w, &http.Cookie{Name: config.cookieName, Value: config.cookieValue})
    cookie, err := req.Cookie(config.cookieName)
    if err != nil {
        log.Println(whereami.WhereAmI(), err.Error())
    }

    log.Println("Cookie: ", cookie)
    http.StripPrefix("/", http.FileServer(http.Dir("./"))).ServeHTTP(w, req)
}

But doing this serves a complete html page:

router.PathPrefix("/").Handler(http.FileServer(http.Dir("./")))
pigfox
  • 1,301
  • 3
  • 28
  • 52
  • 2
    `http.FileServer` returns a `Handler`, which you are discarding, so in this case it does absolutely nothing. Create the `FileServer` once, save it, and pass along the call with `fs.ServeHTTP(w,req)`. And remove the `WriteHeader` call so that the `FileServer` can set the headers and status correctly. – Adrian Jun 09 '20 at 17:33
  • 2
    If it's giving a 404 then whatever path you have in the URL does not line up with the same path in the current working directory (where you've told it to look for the files). – Adrian Jun 09 '20 at 18:03

1 Answers1

0

Like @Adrian mentioned, this seems to be a problem with the location of the file you are expecting to be served. For example, the following code should work as expected with a dir structure

main.go 
index.html
package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
        http.SetCookie(w, &http.Cookie{Name: "foo", Value: "bar"})
        http.StripPrefix("/foo", http.FileServer(http.Dir("./"))).ServeHTTP(w, r)
    })

    panic(http.ListenAndServe(":3030", nil))
}

[Edit]: Strip prefix

poWar
  • 745
  • 6
  • 15
  • @pigfox I have updated the code by stripping the prefix for that handler. Refer [this](https://stackoverflow.com/a/27946132/3473875) to know more about why prefix needs to be stripped. – poWar Jun 09 '20 at 19:17
  • Thanks for the suggestion, it now serves a html file without the css. Code updated. – pigfox Jun 09 '20 at 19:40
  • 1
    @pigfox CSS is served with a different request, check the request sent using browser network console – Shubham Srivastava Jun 10 '20 at 04:53