dinu0101
dinu0101

Reputation: 499

Static content not served with the Gorilla mux router- like style.css,script.js

I am very beginner of Go language. I an trying to serve static containt with Gorrila Mux router. But css and js is not server in my case.

  project
   f-mymux.go 
   d-pages
         f-home.html
         f-about.html
   d-public
        d-css
           f-style.css
        d-js
           f-script.js

Note: f- file & d- directory

My GO code as below:

package main

import (
    "bufio"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "os"
    "strings"
    "text/template"
)

func main() {
    serverWeb()
}

var staticPages = populateStaticPages()

func serverWeb() {
    gorillaRoute := mux.NewRouter().StrictSlash(true)
    gorillaRoute.HandleFunc("/", serveContent)
    gorillaRoute.HandleFunc("/{page_alias}", serveContent)
    gorillaRoute.HandleFunc("/css", serveResource)
    port := ":8080"
    log.Println("Listening at port :", port)
    http.Handle("/", gorillaRoute)
    err := http.ListenAndServe(port, nil)
    if err == nil {
        log.Fatal(err)
    }
}

func serveContent(w http.ResponseWriter, r *http.Request) {
    pathX := r.URL.Path
    log.Println(pathX)
    urlParams := mux.Vars(r)
    page_alias := urlParams["page_alias"]
    if page_alias == "" {
        page_alias = "home"
    }
    staticPage := staticPages.Lookup(page_alias + ".html")
    if staticPage == nil {
        staticPage = staticPages.Lookup("404.html")
        w.WriteHeader(404)
    }
    staticPage.Execute(w, nil)
}

func populateStaticPages() *template.Template {
    result := template.New("template")
    templatePaths := new([]string)
    basePath := "pages"
    templateFolder, _ := os.Open(basePath)
    defer templateFolder.Close()
    templatePathsRow, _ := templateFolder.Readdir(-1)
    for _, pathInfo := range templatePathsRow {
        log.Println(pathInfo.Name())
        *templatePaths = append(*templatePaths, basePath+"/"+
            pathInfo.Name())
    }
    result.ParseFiles(*templatePaths...)
    return result
}

//---------------------------------------------
// Serve resource of types css, js & img files
//---------------------------------------------

func serveResource(w http.ResponseWriter, r *http.Request) {
    path := "./public" + r.URL.Path
    var contentType string
    if strings.HasSuffix(path, ".css") {
        contentType = "text/css; charset=utf-8"
    } /* else if strings.HasSuffix(path , ".png"){
        contentType = "image/png; charset=utf-8"
       } else if strings.HasSuffix(path , ".jpg"){
        contentType = "image/jpg; charset=utf-8"
       } else if strings.HasSuffix(path , ".js"){
       contentType = "application/javascript; charset=utf-8"
       } else {
         contentType = "text/plain; charset=utf-8"
       }*/

    f, err := os.Open(path)
    if err == nil {
        defer f.Close()
        w.Header().Add("Content-Type", contentType)
        br := bufio.NewReader(f)
        br.WriteTo(w)
    } else {
        w.WriteHeader(404)
    }
}

when I am invoking code http://localhost:8080/home then page come witout css and js.When invoking page http://localhost:8080/css/bootstrap.min.css then 404 staus code come

Please help me what am doing wrong here. We can do easily on Java and java server. But on Go lang I spend a whole day but unable to resolve the issue. Your help is appropriated.

Thanks in advance.

Upvotes: 0

Views: 1444

Answers (1)

Dan 0
Dan 0

Reputation: 924

As mkopriva stated, http.FileServer is the way to go. Your public folder can be wherever or whatever you want it to be as long as its referenced properly as the http.FileServer argument.

Adding this would work:

fs := http.FileServer(http.Dir("./public"))
gorillaRoute.PathPrefix("/js/").Handler(fs)
gorillaRoute.PathPrefix("/css/").Handler(fs)

That way a GET request to http://[host]:[port]/css/style.css will return style.css from the relative ./public/css/ directory.

Upvotes: 2

Related Questions