1
0
mirror of https://github.com/mgerb/go-discord-bot synced 2026-01-11 01:22:48 +00:00

switched to gin - use logrus

This commit is contained in:
2018-02-06 18:54:13 +00:00
parent 74976de6cf
commit 5b6d74149d
12 changed files with 116 additions and 212 deletions

View File

@@ -2,19 +2,18 @@ package handlers
import (
"bytes"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"github.com/mgerb/chi_auth_server/response"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
// Downloader -
func Downloader(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url")
fileType := r.FormValue("fileType")
func Downloader(c *gin.Context) {
url := c.Query("url")
fileType := c.Query("fileType")
// create youtube folder if it does not exist
if _, err := os.Stat("youtube"); os.IsNotExist(err) {
@@ -29,8 +28,8 @@ func Downloader(w http.ResponseWriter, r *http.Request) {
err := titleCmd.Run()
if err != nil {
log.Println(err)
response.ERR(w, http.StatusInternalServerError, response.DefaultInternalError)
log.Error(err)
c.JSON(400, err)
return
}
@@ -40,7 +39,7 @@ func Downloader(w http.ResponseWriter, r *http.Request) {
// remove all special characters from title
cleanTitle := cleanseTitle(titleOut.String())
log.Println(cleanTitle)
log.Debug(cleanTitle)
cmd := exec.Command("youtube-dl", "-x", "--audio-format", "mp3", "-o", "./youtube/"+cleanTitle+".%(ext)s", url)
@@ -50,13 +49,13 @@ func Downloader(w http.ResponseWriter, r *http.Request) {
err = cmd.Run()
if err != nil {
log.Println(out.String())
log.Println(err)
response.ERR(w, http.StatusInternalServerError, response.DefaultInternalError)
log.Error(out.String())
log.Error(err)
c.JSON(400, err)
return
}
response.JSON(w, map[string]interface{}{"fileName": cleanTitle + "." + fileType})
c.JSON(200, map[string]interface{}{"fileName": cleanTitle + "." + fileType})
}
func cleanseTitle(title string) string {
@@ -64,7 +63,7 @@ func cleanseTitle(title string) string {
// Make a Regex to say we only want
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatal(err)
log.Error(err)
}
return reg.ReplaceAllString(title, "")

View File

@@ -2,13 +2,13 @@ package handlers
import (
"io/ioutil"
"log"
"strings"
"net/http"
"github.com/mgerb/chi_auth_server/response"
"github.com/gin-gonic/gin"
"github.com/mgerb/go-discord-bot/server/config"
log "github.com/sirupsen/logrus"
)
var soundList []sound
@@ -20,17 +20,17 @@ type sound struct {
}
// SoundList -
func SoundList(w http.ResponseWriter, r *http.Request) {
func SoundList(c *gin.Context) {
if len(soundList) < 1 {
err := PopulateSoundList()
if err != nil {
response.ERR(w, http.StatusInternalServerError, []byte(response.DefaultInternalError))
c.JSON(http.StatusInternalServerError, err)
return
}
}
response.JSON(w, soundList)
c.JSON(200, soundList)
}
// PopulateSoundList -
@@ -61,15 +61,15 @@ func PopulateSoundList() error {
}
// ClipList -
func ClipList(w http.ResponseWriter, r *http.Request) {
func ClipList(c *gin.Context) {
clipList := []sound{}
files, err := ioutil.ReadDir(config.Config.ClipsPath)
if err != nil {
log.Println(err)
response.ERR(w, 500, response.DefaultInternalError)
log.Error(err)
c.JSON(http.StatusInternalServerError, err)
return
}
@@ -85,5 +85,5 @@ func ClipList(w http.ResponseWriter, r *http.Request) {
clipList = append(clipList, listItem)
}
response.JSON(w, clipList)
c.JSON(200, clipList)
}

View File

@@ -1,67 +1,54 @@
package handlers
import (
"io"
"os"
"strings"
"net/http"
"github.com/mgerb/chi_auth_server/response"
"github.com/gin-gonic/gin"
"github.com/mgerb/go-discord-bot/server/config"
log "github.com/sirupsen/logrus"
)
// FileUpload
func FileUpload(w http.ResponseWriter, r *http.Request) {
func FileUpload(c *gin.Context) {
password := r.FormValue("password")
password := c.PostForm("password")
if string(password) != config.Config.UploadPassword {
response.ERR(w, http.StatusInternalServerError, []byte("Invalid password."))
c.JSON(http.StatusInternalServerError, "Invalid password.")
return
}
file, header, err := r.FormFile("file")
file, err := c.FormFile("file")
if err != nil {
response.ERR(w, http.StatusInternalServerError, []byte("Error reading file."))
log.Error(err)
c.JSON(http.StatusInternalServerError, "Error reading file.")
return
}
defer file.Close()
src, err := header.Open()
if err != nil {
response.ERR(w, http.StatusInternalServerError, []byte("Error opening file."))
return
}
defer src.Close()
// create uploads folder if it does not exist
if _, err := os.Stat(config.Config.SoundsPath); os.IsNotExist(err) {
os.Mkdir(config.Config.SoundsPath, os.ModePerm)
}
// convert file name to lower case and trim spaces
header.Filename = strings.ToLower(header.Filename)
header.Filename = strings.Replace(header.Filename, " ", "", -1)
file.Filename = strings.ToLower(file.Filename)
file.Filename = strings.Replace(file.Filename, " ", "", -1)
// check if file already exists
if _, err := os.Stat(config.Config.SoundsPath + header.Filename); err == nil {
response.ERR(w, http.StatusInternalServerError, []byte("File already exists."))
if _, err := os.Stat(config.Config.SoundsPath + file.Filename); err == nil {
c.JSON(http.StatusInternalServerError, "File already exists.")
return
}
dst, err := os.Create(config.Config.SoundsPath + header.Filename)
err = c.SaveUploadedFile(file, config.Config.SoundsPath+file.Filename)
log.Debug("Saving file", config.Config.SoundsPath+file.Filename)
if err != nil {
response.ERR(w, http.StatusInternalServerError, []byte("Error creating file."))
return
}
defer dst.Close()
if _, err = io.Copy(dst, src); err != nil {
response.ERR(w, http.StatusInternalServerError, []byte("Error writing file."))
log.Error(err)
c.JSON(http.StatusInternalServerError, "Error creating file.")
return
}
@@ -69,9 +56,10 @@ func FileUpload(w http.ResponseWriter, r *http.Request) {
err = PopulateSoundList()
if err != nil {
response.ERR(w, http.StatusInternalServerError, []byte("Error populating sound list."))
log.Error(err)
c.JSON(http.StatusInternalServerError, "Error populating sound list.")
return
}
response.JSON(w, []byte("Success"))
c.JSON(200, "Success")
}

View File

@@ -1,13 +1,12 @@
package pubg
import (
"log"
"net/http"
"sync"
"time"
"github.com/mgerb/chi_auth_server/response"
"github.com/gin-gonic/gin"
pubgClient "github.com/mgerb/go-pubg"
log "github.com/sirupsen/logrus"
)
var (
@@ -21,7 +20,7 @@ func Start(key string, players []string) {
apiKey = key
log.Println("Gathering pubg data...")
log.Debug("Gathering pubg data...")
go fetchStats(players)
}
@@ -41,7 +40,7 @@ func fetchStats(players []string) {
newStats, err := api.GetPlayer(player)
if err != nil {
log.Println(err)
log.Error(err)
continue
}
@@ -58,6 +57,6 @@ func fetchStats(players []string) {
}
// Handler - returns the pubg stats
func Handler(w http.ResponseWriter, r *http.Request) {
response.JSON(w, stats)
func Handler(c *gin.Context) {
c.JSON(200, stats)
}

View File

@@ -1,53 +1,32 @@
package webserver
import (
"log"
"net/http"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/acme/autocert"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/gin-gonic/gin"
"github.com/mgerb/go-discord-bot/server/config"
"github.com/mgerb/go-discord-bot/server/webserver/handlers"
"github.com/mgerb/go-discord-bot/server/webserver/pubg"
)
func getRouter() *chi.Mux {
func getRouter() *gin.Engine {
router := gin.Default()
r := chi.NewRouter()
router.Static("/static", "./dist/static")
router.Static("/public/sounds", config.Config.SoundsPath)
router.Static("/public/youtube", "./youtube")
router.Static("/public/clips", config.Config.ClipsPath)
r.Use(middleware.RequestID)
r.Use(middleware.DefaultCompress)
if !config.Flags.Prod {
r.Use(middleware.Logger)
}
workDir, _ := os.Getwd()
FileServer(r, "/static", http.Dir(filepath.Join(workDir, "./dist/static")))
FileServer(r, "/public/sounds", http.Dir(filepath.Join(workDir, config.Config.SoundsPath)))
FileServer(r, "/public/youtube", http.Dir(filepath.Join(workDir, "./youtube")))
FileServer(r, "/public/clips", http.Dir(filepath.Join(workDir, config.Config.ClipsPath)))
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./dist/index.html")
router.NoRoute(func(c *gin.Context) {
c.File("./dist/index.html")
})
r.Route("/api", func(r chi.Router) {
// configure api end points
r.Get("/soundlist", handlers.SoundList)
r.Get("/cliplist", handlers.ClipList)
r.Put("/upload", handlers.FileUpload)
r.Get("/ytdownloader", handlers.Downloader)
r.Get("/stats/pubg", pubg.Handler)
})
api := router.Group("/api")
api.GET("/stats/pubg", pubg.Handler)
api.GET("/ytdownloader", handlers.Downloader)
api.GET("/soundlist", handlers.SoundList)
api.GET("/cliplist", handlers.ClipList)
api.POST("/upload", handlers.FileUpload)
return r
return router
}
// Start -
@@ -59,49 +38,5 @@ func Start() {
}
router := getRouter()
if config.Flags.TLS {
// start server on port 80 to redirect
go http.ListenAndServe(":80", http.HandlerFunc(redirect))
// start TLS server
log.Fatal(http.Serve(autocert.NewListener(), router))
} else {
// start basic server
http.ListenAndServe(config.Config.ServerAddr, router)
}
}
// FileServer conveniently sets up a http.FileServer handler to serve
// static files from a http.FileSystem.
func FileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters.")
}
fs := http.StripPrefix(path, http.FileServer(root))
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
}))
}
// redirect to https
func redirect(w http.ResponseWriter, req *http.Request) {
// remove/add not default ports from req.Host
target := "https://" + req.Host + req.URL.Path
if len(req.URL.RawQuery) > 0 {
target += "?" + req.URL.RawQuery
}
http.Redirect(w, req, target, http.StatusTemporaryRedirect)
router.Run(config.Config.ServerAddr)
}