我想在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:])
}
Run Code Online (Sandbox Code Playgroud)
然后在这里引用它:
...
...
http.HandleFunc("/", handler)
Run Code Online (Sandbox Code Playgroud)
现在,我想做的是提供图像而不是写入字符串.我该怎么办?
Int*_*net 23
您可以使用该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)
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:更惯用的代码.
编辑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")))).