ZetCode

Go HTTP serve image

last modified February 8, 2022

Go HTTP serve image tutorial shows how to serve an image from a Golang server.

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP protocol is the foundation of data communication for the World Wide Web.

The net/http package provides HTTP client and server implementations and is used to create GET and POST requests.

Go serve image example

In the first example, we simply send an image as a stream of bytes.

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

The example creates a simple web server that sends an image to the client. The image is located in the current working directory.

handler := http.HandlerFunc(handleRequest)

http.Handle("/image", handler)

We map a handler to the /image path.

func handleRequest(w http.ResponseWriter, r *http.Request) {
...

The handler function accepts two parameters: http.ResponseWriter and http.Request.

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

We read the image into the buffer.

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

We set the header. The Content-Type content type is used for PNG image.

w.Write(buf)

The image data is written to the response body with Write.


In the next example, we send the image as an attachment.

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

To send the file as an attachment, we set the Content-Disposition header. We choose the attachment option and provide the filename.

Go serve image example II

In the next example, the image is send within an HTML document.

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>

The image is referenced from the img tag.

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

We serve the image.html file for the /image path.

fs := http.FileServer(http.Dir("./data"))
http.Handle("/data/", http.StripPrefix("/data/", fs))

The file server serves static data from the data subdirectory. URL paths starting with /data are directed to this subdirectory.

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

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

The HTML file is served with http.ServeFile.

In this tutorial, we have served images from a HTTP server in Golang.

List all Go tutorials.