ZetCode

Go HTTP 提供图片

最后修改时间 2024 年 4 月 11 日

在本文中,我们将展示如何从 Golang 服务器提供图片。

超文本传输协议(Hypertext Transfer Protocol (HTTP))是一种用于分布式、协作式、超媒体信息系统的应用层协议。HTTP 协议是万维网数据通信的基础。

net/http 包提供了 HTTP 客户端和服务器实现,用于创建 GET 和 POST 请求。

Go 提供图片示例

在第一个示例中,我们仅将图片作为字节流发送。

main.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.ResponseWriterhttp.Request

buf, err := ioutil.ReadFile("sid.png")

我们将图片读入缓冲区。

w.Header().Set("Content-Type", "image/png")

我们设置了头部。Content-Type 内容类型用于 PNG 图片。

w.Write(buf)

图片数据通过 Write 写入响应体。


在下一个示例中,我们将图片作为附件发送。

main.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.Header().Set("Content-Disposition", `attachment;filename="sid.png"`)

    w.Write(buf)
}

要将文件作为附件发送,我们需要设置 Content-Disposition 标头。我们选择 attachment 选项并提供文件名。

Go 提供图片示例 II

在下一个示例中,图片嵌入在 HTML 文档中发送。

image.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 标签引用。

main.go
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 子目录提供静态数据。以 /data 开头的 URL 路径将定向到此子目录。

http.HandleFunc("/image", func(w http.ResponseWriter, r *http.Request) {

    http.ServeFile(w, r, "image.html")
})

HTML 文件使用 http.ServeFile 提供。

来源

Go net/http 包 - 参考

在本文中,我们从 Golang 的 HTTP 服务器提供了图片。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出所有 Go 教程