dpziir0079 2017-10-01 18:28
浏览 36

大猩猩多路复用器路由器不提供静态内容,例如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.

  • 写回答

1条回答 默认 最新

  • dopod0901 2017-10-02 04:40
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么