Configure Static Files

Configure Static Files

Static files in Gin is fairly straight forward.

Serve a folder

Assuming your folder structure looks like this

      • file.png
      • favicon.svg
    • go.mod
    • go.sum
  • main.go
    func main() {
    	router := gin.Default()
    
        // First argument is the GET Route prefix for static files
    	router.Static("/assets", "./public")
    
    	router.Run(":8080")
    }

    Visit http://localhost:8080/assets/file.png on a browser to verify.

    Serve a single file

    Here is how to serve only a single file in Gin

    main.go
    router.StaticFile("/favicon.svg", "./public/favicon.svg")

    Visit http://localhost:8080/favicon.svg on a browser to verify. or you can curl it :)

    Advanced ( use custom file systems )

    main.go
    router.StaticFS("/more_static", http.Dir("filesystem"))
    Last updated on