资产和文件

嗨,我是 Philipp!
我想告诉你,我的平台 Go Web 示例课程 刚刚上线。享受关于 Go 中 Web 开发的易于理解的视频课程。一定要查看我为早期支持者提供的特别优惠。
我们会在那里见面的!:)
了解更多

资产和文件

此示例将展示如何从特定目录提供静态文件,例如 CSS、JavaScript 或图像。

// static-files.go
package main

import "net/http"

func main() {
    fs := http.FileServer(http.Dir("assets/"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.ListenAndServe(":8080", nil)
}
$ tree assets/
assets/
└── css
    └── styles.css
$ go run static-files.go

$ curl -s http://localhost:8080/static/css/styles.css
body {
    background-color: black;
}