Skip to content

Instantly share code, notes, and snippets.

@thesunwave
Created December 2, 2019 21:08
Show Gist options
  • Save thesunwave/f1e2d1a3f5d4b3644c28c05f03aced4d to your computer and use it in GitHub Desktop.
Save thesunwave/f1e2d1a3f5d4b3644c28c05f03aced4d to your computer and use it in GitHub Desktop.
local files runner on golang
package main
import (
"bytes"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/parsiya/golnk"
"io/ioutil"
"log"
"os/exec"
"path/filepath"
)
func main() {
Server()
}
func Server() {
r := gin.Default()
r.GET("/run", func(c *gin.Context) {
requredFile := c.Query("file")
err := runFile(requredFile)
if err != nil {
c.JSON(422, gin.H{
"error": err.Error(),
})
} else {
c.JSON(200, gin.H{
"message": "File is running",
})
}
})
r.GET("/list", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": locateFiles(),
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
func findFile(name string, fileList []string) error {
for _, v := range fileList {
if v == name {
return nil
}
}
return errors.New("file not found")
}
func runFile(name string) error {
err := findFile(name, locateFiles())
if err != nil {
return err
}
if filepath.Ext(name) == ".lnk" {
lnk, err := lnk.File(name)
if err != nil {
return nil
}
name = lnk.LinkInfo.LocalBasePath
} else {
name = fmt.Sprintf("./%s", name)
}
command := exec.Command(name)
// set var to get the output
var out bytes.Buffer
// set the output to our variable
command.Stdout = &out
err = command.Run()
if err != nil {
log.Println(err)
return err
}
fmt.Println(out.String())
return nil
}
func locateFiles() []string {
files, err := ioutil.ReadDir("./")
if err != nil {
log.Fatal(err)
}
var filesList []string
for _, f := range files {
filesList = append(filesList, f.Name())
fmt.Println(f.Name())
}
return filesList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment