How do I serve CSS and JS in Go

I followed the Go Writing Web Applications tutorial , but for some reason I was having trouble getting a CSS and JS service application. If I run my static page without a Go server, the CSS of the page works fine. On the other hand, when I start the Go server, CSS just doesn't work.

This is what my HTML looks like:

<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="../assets/css/custom.css">

then under the tag body:

<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>

My file tree looks like this:

go-affect/
β”œβ”€β”€ data
β”‚   └── …
β”œβ”€β”€ static
β”‚   β”œβ”€β”€ css
β”‚   β”‚   └── …
β”‚   └── js
β”‚   β”‚   └── …
β”œβ”€β”€ tmpl
β”‚   β”œβ”€β”€ edit.html
β”‚   β”œβ”€β”€ index.html
β”‚   └── view.html
└── main.go

How do I get my Go app to serve the CSS and JavaScript I need?

Since then, the problem has been resolved, here is the main working one:

func main() {
    http.HandleFunc("/view/", makeHandler(viewHandler))
    http.HandleFunc("/edit/", makeHandler(editHandler))
    http.HandleFunc("/save/", makeHandler(saveHandler))
    http.HandleFunc("/index/", makeHandler(indexHandler))


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

    http.ListenAndServe(":8080", nil)
}

Here is an example of the handlers I use:

func indexHandler(w http.ResponseWriter, r *http.Request, title string) {
    p := &Page{Title: title}
    err := templates.ExecuteTemplate(w, "index.html", p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}
+14
source share
2 answers
http.Handle("/", http.FileServer(http.Dir("css/")))

css /. , .

, , , , - .

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

js css static . domain.com/static/css/filename.css domain.com/static/js/filename.js

StripPrefix , , , static static/css/filename.css , , . css/filename.css static , .

+19

Apache css dir head . , go, dir, go. cgi-bin.

CSS Apache Server assets/css:

<link rel="stylesheet" href="/assets/css/main.css" />

cgi-bin

sytle apache/css dir

0

Source: https://habr.com/ru/post/1016741/


All Articles