如何从Golang服务器提供图像

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.ResponseWriterhttp.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教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏