Last active
September 6, 2022 15:59
-
-
Save aufi/92ce917ac93c7b82a5e0fe2153683a34 to your computer and use it in GitHub Desktop.
gin tar gz on the fly sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"archive/tar" | |
"bufio" | |
"bytes" | |
"compress/gzip" | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"path/filepath" | |
"regexp" | |
"github.com/gin-gonic/gin" | |
) | |
var db = make(map[string]string) | |
func setupRouter() *gin.Engine { | |
// Disable Console Color | |
// gin.DisableConsoleColor() | |
r := gin.Default() | |
// Ping test | |
r.GET("/ping", func(c *gin.Context) { | |
c.String(http.StatusOK, "pong") | |
}) | |
// Get user value | |
r.GET("/buckets/:ID", func(ctx *gin.Context) { | |
invalidSymbols := regexp.MustCompile("[^a-zA-Z0-9-_]") | |
bucketID := invalidSymbols.ReplaceAllString(ctx.Param("ID"), "") | |
fmt.Printf(fmt.Sprintf("Using bucket: %s", bucketID)) | |
if _, err := os.Stat("/tmp/bucket/" + bucketID); os.IsNotExist(err) { | |
ctx.JSON(http.StatusNotFound, "Bucket doesn't exist.") | |
return | |
} | |
fmt.Printf("Using bucket path") | |
var tarOutput bytes.Buffer | |
tarWriter := tar.NewWriter(&tarOutput) | |
err := filepath.Walk("/tmp/bucket/"+bucketID, func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
fmt.Println(err) | |
return err | |
} | |
fmt.Printf("dir: %v: name: %s\n", info.IsDir(), path) | |
if !info.IsDir() { | |
file, _ := os.Open(path) | |
hdr, err := tar.FileInfoHeader(info, path) | |
if err != nil { | |
panic(err) | |
} | |
if err := tarWriter.WriteHeader(hdr); err != nil { | |
log.Fatal(err) | |
} | |
if _, err = io.Copy(tarWriter, file); err != nil { | |
log.Fatal(err) | |
} | |
} | |
return nil | |
}) | |
if err := tarWriter.Close(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("ADDED FILES done") | |
if err != nil { | |
fmt.Println(err) | |
} | |
fromTar := bufio.NewReader(&tarOutput) | |
ctx.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", bucketID+".tar.gz")) | |
gzWriter := gzip.NewWriter(ctx.Writer) | |
defer gzWriter.Close() | |
gzWriter.Name = bucketID + ".tar.gz" | |
gzWriter.Comment = "MMMMMMM bucket data archive" | |
if _, err := io.Copy(gzWriter, fromTar); err != nil { | |
fmt.Println(err) | |
} | |
}) | |
return r | |
} | |
func main() { | |
r := setupRouter() | |
// Listen and Server in 0.0.0.0:8080 | |
r.Run(":8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment