用 Golang 中的 Gin 提供文件服务

时间:2024-02-06

浏览:228

作者:佚名

今天golang学习网给大家带来了《用 Golang 中的 Gin 提供文件服务》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我想提供动态加载的用户文件(让我们假设简单的文件存储),但我想在发送实际文件之前添加一些检查(就像用户被禁止一样)。我知道有一种方法可以在 gin 中提供整个目录,还有一种方法可以将文件作为附件发送(how to server a file from a handler in golang),但是有没有一种方法可以简单地将文件作为实际图像发送回以显示在浏览器(没有下载附件提示)如这个纯 golang 示例(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
}


正确答案


是的,go-gin 是可以实现的。您可以使用 gin 上下文的 data 方法。

data 将一些数据写入正文流并更新 http 代码。

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

检查gin提供的示例代码本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页