Golang Gin service sample
- listdir.go
/*
* Author, Copyright: Oleg Borodin <onborodin@gmail.com>
*/
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"fmt"
"log"
"path/filepath"
"os"
"path"
"time"
)
type File struct {
Name string `json:"name"`
Size int64 `json:"size"`
}
func listDir (dir string, glob string) []File {
files, err := filepath.Glob(path.Join(dir, glob))
if err != nil {
log.Fatal(err)
}
list := []File{}
for i := 0; i < len(files); i++ {
name := files[i]
fi, err := os.Stat(name);
if err != nil {
log.Fatal(err)
continue
}
if fi.IsDir() {
continue
}
item := File{
Name: fi.Name(),
Size: fi.Size(),
}
list = append(list, item)
}
return list
}
func logFormatter() func(param gin.LogFormatterParams) string {
return func(param gin.LogFormatterParams) string {
return fmt.Sprintf("%s - [%s] %s %s %s %d %s \"%s\" \"%s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC3339),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
param.Request.UserAgent(),
param.ErrorMessage,
)
}
}
func main() {
gin.SetMode(gin.ReleaseMode)
gin.DisableConsoleColor()
router := gin.New()
router.Use(gin.LoggerWithFormatter(logFormatter()))
router.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "hello",
})
})
router.GET("/dir", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"result" : listDir("/data/music", "*"),
})
})
router.Run(":8089")
}
output
# curl -v http://localhost:8089/dir
* Connected to localhost (127.0.0.1) port 8089 (#0)
> GET /dir HTTP/1.1
> Host: localhost:8089
> User-Agent: curl/7.63.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Fri, 22 Nov 2019 10:15:40 GMT
< Content-Length: 547
<
{
"result":[
{
"name":"David Bowie - Absolute Beginners.mp4",
"size":32710112
},
{
"name":"David Bowie - As The World Falls Down.mp4",
"size":12703944
},
{
"name":"David Bowie - Ashes To Ashes.mp4",
"size":21878520
},
{
"name":"David Bowie - Blue Jean.mp4",
"size":17056138
},
{
"name":"David Bowie - Space Oddity, Live, 1969.mp4",
"size":11829366
},
{
"name":"David Bowie - Time Will Crawl.mp4",
"size":28125356
},
{
"name":"Neil Young Harvest 1972 Full Album (no ads).ogg",
"size":33582434
},
]
}




