'Set base path for follow-up HTTP request

Suppose there is a file called foo.html and a project structure that looks like this:

|--styles
|    |--style.css 📜
|--pages
|    |--foo.html 📜

foo.html contains (among other stuff):

    <link rel="stylesheet" type="text/css" href="styles/style.css">

Now, when the client requests for pages/foo.html, it will see the link to the css file and it will make a follow-up request to pages/styles/style.css. Is there a way I can instead tell it from the file server to make a request to styles/style.css rather than pages/styles/style.css? I'm using the Go http library from the standard library.



Solution 1:[1]

I guess you are already using http go package. Here is the below sample code which can help you to achieve what you intend to do:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func hello(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "hello1\n")
}

func main() {
    fs := http.FileServer(http.Dir("./page/static"))
    http.Handle("/page/styles/", http.StripPrefix("/page/styles/", fs))

    page_fs := http.FileServer(http.Dir("./page"))
    http.Handle("/page/", http.StripPrefix("/page/", page_fs))

    http.HandleFunc("/hello", hello)
    log.Println("Listening on :3000...")
    err := http.ListenAndServe(":3000", nil)
    if err != nil {
        log.Fatal(err)
    }
}

Let me know if you need explanation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1