Created
January 17, 2022 10:58
-
-
Save abhilashsajeev/968a9aa39af25ec82ec313403ec7fe05 to your computer and use it in GitHub Desktop.
Simple File Server using golang
This file contains 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 ( | |
"log" | |
"fmt" | |
"os" | |
"path/filepath" | |
"net/http" | |
"github.com/gin-gonic/gin" | |
) | |
func main() { | |
r := gin.Default() | |
r.GET("/", func(c *gin.Context) { | |
c.JSON(http.StatusOK, gin.H{"data": "hello world"}) | |
}) | |
r.GET("/file", func(c *gin.Context){ | |
file_path := c.Query("file_path") | |
log.Println("file name receievd--->", file_path) | |
c.File(file_path) | |
}) | |
r.POST("/upload", func(c *gin.Context) { | |
// Single file | |
file, err := c.FormFile("file") | |
filePath := c.PostForm("file_path") | |
if err != nil { | |
c.String(http.StatusBadRequest, "get form err: %s", err.Error()) | |
return | |
} | |
log.Println("file name receievd in post", err) | |
log.Println("file name Path ------->", filePath) | |
log.Println("file name receievd", file.Filename) | |
filename := filepath.Base(file.Filename); | |
if filePath != "" { | |
filename = filepath.Join(filePath, file.Filename); | |
} | |
if _, err := os.Stat(filePath); os.IsNotExist(err) { | |
err := os.Mkdir(filePath, os.ModePerm) | |
if err != nil { | |
log.Println("mkdir err", err) | |
} | |
} | |
if err := c.SaveUploadedFile(file, filename); err != nil { | |
c.String(http.StatusBadRequest, "upload file err: %s", err.Error()) | |
return | |
} | |
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) | |
}) | |
r.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment