1

I would like to serve dynamically loaded user files (let's assume simple file storage) but I want to add some checks before sending actual file (like was the user banned). I know there is a way to serve whole directory in gin, there is also way to send file as attachment (How to server a file from a handler in golang) but is there a way to simply send back file as actual image to show in browser (without download attachment prompt) as in this pure golang example (https://golangbyexample.com/image-http-response-golang/):

package main

import (
    "io/ioutil"
    "net/http"
)

func main() {
    handler := http.HandlerFunc(handleRequest)
    http.Handle("/photo", handler)
    http.ListenAndServe(":8080", nil)
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    fileBytes, err := ioutil.ReadFile("test.png")
    if err != nil {
        panic(err)
    }
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/octet-stream")
    w.Write(fileBytes)
    return
}
asdfgh
  • 2,823
  • 4
  • 21
  • 26

1 Answers1

2

Yes, it is possible with go-gin. You can use Data method of gin context.

Data writes some data into the body stream and updates the HTTP code.

import (
    "io/ioutil"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/photo", photoHandler)

    if err := r.Run(":8080"); err != nil {
        panic(err)
    }
}

func photoHandler(c *gin.Context) {

    // do the other checks here

    // read the file
    fileBytes, err := ioutil.ReadFile("test.png")
    if err != nil {
        panic(err)
    }

    
    c.Data(http.StatusOK, "image/png", fileBytes)
}

Check gin provided sample code here

PRATHEESH PC
  • 1,461
  • 1
  • 3
  • 15