go-lang简单的web服务器:提供静态图片服务

huangapple go评论112阅读模式
英文:

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"))))

Playground

英文:

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")))).

Playground

huangapple
  • 本文由 发表于 2013年5月21日 22:31:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/16672593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定