英文:
go-lang simple webserver : serve static image
问题
我想用Go语言编写一个简单的Web服务器,实现以下功能:当我访问http://example.go:8080/image时,返回一个静态图片。
我正在按照我在这里找到的示例进行操作。在这个示例中,他们实现了以下方法:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
然后在这里引用它:
...
...
http.HandleFunc("/", handler)
现在,我想返回一张图片而不是写入字符串。我该如何操作?
英文:
I want to write a simple webserver in go that does the following: when i go to http://example.go:8080/image, it returns a static image.
I'm following an example i found here. In this example they implement this method:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
and then refer to it here :
...
...
http.HandleFunc("/", handler)
Now, what i wanna do is serve an image instead of writing to the string.
How would i go about that?
答案1
得分: 28
你可以使用http.FileServer
函数来提供静态文件。
package main
import (
"log"
"net/http"
)
func main() {
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("path/to/file"))))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
编辑:更加惯用的代码。
编辑2:当浏览器请求http://example.go/image.png时,上述代码将返回一个名为image.png
的图片。
在这种情况下,http.StripPrefix
函数是多余的,因为处理的路径是网站根目录。如果要从路径http://example.go/images/image.png提供图片,则上述代码需要改为http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("path/to/file"))))
。
英文:
You can serve static files using the http.FileServer
function.
package main
import (
"log"
"net/http"
)
func main() {
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("path/to/file"))))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
EDIT: More idiomatic code.
EDIT 2: This code above will return an image image.png
when the browser requests http://example.go/image.png
The http.StripPrefix
function here is strictly unnecessary in this case as the path being handled is the web root. If the images were to be served from the path http://example.go/images/image.png then the line above would need to be http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("path/to/file"))))
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论