LoginSignup
2
0

More than 1 year has passed since last update.

【Go/Gin】画像を返すAPI

Last updated at Posted at 2022-12-17

imagesフォルダにある画像を
(ルートURL)/(任意のパス)/(画像名)
にアクセスすることによって返してくれるAPIを作りました。

フォルダ構成

root
├ images
    ├imageA.png
    └imageB.png
└main.go

コーディング

main.go
package main

import (
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
)

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

	//画像を返す
	router.GET("/api/Image/:imageID", HandlerImage)

	router.Run()
}

func HandlerImage(ctx *gin.Context) {
	imageID := ctx.Param("imageID")

    //パスをここで指定
    path := "/images/" * imageID + ".png"

    //ここで画像を返す
	ctx.File(path)
}

要するに、ctx.File(ファイルのパス)で返せるというだけです。

このmain.goを実行して、
localhost:8080/api/Image/imageA
にアクセスすると、imagesフォルダのimageA.pngが表示されます。めでたしめでたし。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0