douan4106 2016-02-25 22:47
浏览 219

在Golang中访问静态文件


I am having trouble linking to an external CSS file in one of my served pages in a Go Server.

This is my project structure, with some comments. My $GOPATH, is the top-level directory. Note that there is a "main" executable that was built via using the "$go build main" command from this top-level directory. It essentially compiled the files in the src/main directory. I then run the program directly through this executable ("$.\main").

.
├── bin
├── main <-- Executable, not directory (built via "go build main")
├── pkg
│   └── darwin_amd64
├── src
│   ├── github.com
│   └── main <---- My Go files are here!
├── style
│   └── style.css
└── templates
    └── developers.html

I am trying to use the style.css file as an externally linked style file in the developers.html template, that is eventually parsed and merged by Go. The files are listed below, in simplified versions.

developers.html

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style/style.css">
    </head>
    <body>
        ...
    </body>
</html>

server.go

package main

import (
    "log"
    "net/http"
)

func main() {
    styleHandler := http.FileServer(http.Dir("style"))
    http.Handle("/style/", http.StripPrefix("/style/", styleHandler))

    // router handles other non-static pages, 
    // and is defined in another .go source file. These are working.
    router := MainRouter()
    log.Fatal(http.ListenAndServe(":8080", router))
}

I'm sure the problem is how I'm treating the relative paths, but I can't figure it out. Thanks for any help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)