15

我想在 go 中编写一个简单的网络服务器,它执行以下操作:当我转到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)

现在,我想做的是提供图像而不是写入字符串。我该怎么办?

4

1 回答 1

26

您可以使用该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:image.png当浏览器请求http://example.go/image.png时,上面的代码将返回一个图像

在这种情况下,这里的http.StripPrefix函数是完全不需要的,因为正在处理的路径是 Web 根目录。如果要从路径http://example.go/images/image.png提供图像,那么上面的行需要是http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("path/to/file")))).

操场

于 2013-05-21T14:35:31.167 回答