'How to prevent static resources from being accessed directly in golang http.FileServer?
have a nice day! I sincerely ask for your advice and help. I use the back end written by golang. I hope my web page can load CSS and pictures. I use the following methods:
fs := http. FileServer(http.Dir("mystatic/"))
http. Handle("/static/", http.StripPrefix("/static/", fs))
Then I load CSS and images in the following way:
<img src= "/static/img/name_of_picture.jpeg" class="img-fluid" alt="fail" >
<link href="/static/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
However, there is a serious problem that static resources will be accessed by the client using the URL plus /static/, and all my CSS and pictures will be accessed and downloaded directly. How can I prevent the client from accessing these resources directly?
I tried to use nginx to prohibit access to /static/, but the web page was also blocked and could not load CSS and pictures. I noticed that other websites should use methods to prohibit direct access to the static resources of the website (the web page display has no permission), but I tried for several days and failed, and I don't know what keywords to use to find the answer, I really hope you can guide me on how to prevent customers from directly using the website and /static/ accessing my static resources. Thank you very much!
//----------------------------------------------------------------
Additional notes:
I have an idea that I can directly read and write pictures to the website, but I don't know how to write multiple pictures in a web page in the way of data stream in golang;
And I don't know how to use golang to read CSS files directly according to the real path, and then return to the web page?
codes:
func go_ web_ webs1_ (w http.ResponseWriter, r *http.Request) {
t, _ := template. ParseFiles("static/web/basic.html", "static/web/body.html")
t.Execute(w, nil)
}
If the image can be loaded using the following,
func showPicHandle( w http.ResponseWriter, req *http.Request ) {
file, err := os. Open("." + req. URL. Path)
errorHandle(err, w);
defer file. Close()
buff, err := ioutil. ReadAll(file)
errorHandle(err, w);
w.Write(buff)
}
Then I can write the image directly to the page without using static resources, but I don't know how to load several images this way, and return them to the above htmls at the same time
t, _ := template. ParseFiles("static/web/basic.html", "static/web/body.html")
I wonder if the above idea is also a solution, and how it should be implemented?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
