GoHTTP服务图像教程展示了如何从Golang服务器提供图像。
超文本传输协议(HTTP)是分布式协作超媒体信息系统的应用协议。HTTP协议是万维网数据通信的基础。
net/http
包提供HTTP客户端和服务器实现,用于创建GET和POST请求。
$ go version go version go1.18.1 linux/amd64
我们使用Go版本1.18。
Go服务图像示例
在第一个示例中,我们只是将图像作为字节流发送。
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { handler := http.HandlerFunc(handleRequest) http.Handle("/image", handler) fmt.Println("Server started at port 8080") http.ListenAndServe(":8080", nil) } func handleRequest(w http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadFile("sid.png") if err != nil { log.Fatal(err) } w.Header().Set("Content-Type", "image/png") w.Write(buf) }
该示例创建了一个简单的Web服务器,用于向客户端发送图像。该图像位于当前工作目录中。
handler := http.HandlerFunc(handleRequest) http.Handle("/image", handler)
我们将处理程序映射到/image
路径。
func handleRequest(w http.ResponseWriter, r *http.Request) { ...
处理函数接受两个参数:http.ResponseWriter
和http.Request
。
buf, err := ioutil.ReadFile("sid.png")
我们将图像读入缓冲区。
w.Header().Set("Content-Type", "image/png")
我们设置标题。Content-Type
内容类型用于PNG图像。
w.Write(buf)
图像数据通过Write
写入响应体。
在下一个示例中,我们将图像作为附件发送。
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { handler := http.HandlerFunc(handleRequest) http.Handle("/image", handler) fmt.Println("Server started at port 8080") http.ListenAndServe(":8080", nil) } func handleRequest(w http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadFile("sid.png") if err != nil { log.Fatal(err) } w.Header().Set("Content-Type", "image/png") w.Header().Set("Content-Disposition", `attachment;filename="sid.png"`) w.Write(buf) }
为了将文件作为附件发送,我们设置了Content-Disposition
标头。我们选择附件
选项并提供文件名。
GoserveimageexampleII
在下一个示例中,图像在HTML文档中发送。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home page</title> </head> <body> <p>Sid</p> <img src="data/sid.png" alt="Sid the sloth"> </body> </html>
图像是从img
标签中引用的。
package main import ( "fmt" "net/http" ) func main() { fs := http.FileServer(http.Dir("./data")) http.Handle("/data/", http.StripPrefix("/data/", fs)) http.HandleFunc("/image", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "image.html") }) fmt.Println("Server started at port 8080") http.ListenAndServe(":8080", nil) }
我们为/image
路径提供image.html
文件。
fs := http.FileServer(http.Dir("./data")) http.Handle("/data/", http.StripPrefix("/data/", fs))
文件服务器提供数据子目录中的静态数据。以/data
开头的URL路径指向此子目录。
http.HandleFunc("/image", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "image.html") })
HTML文件由http.ServeFile
提供。
在本教程中,我们使用Golang提供来自HTTP服务器的图像。
列出所有Go教程。