From 769d8f08b86f066cfb16bee9c45b204e57be09dd Mon Sep 17 00:00:00 2001 From: Nikolay Kasyanov <65883674+Unbewohnte@users.noreply.github.com> Date: Thu, 27 May 2021 09:01:28 +0300 Subject: [PATCH] Add files via upload --- fileServer/LICENSE | 9 +++++ fileServer/README.md | 17 ++++++++++ fileServer/go.mod | 3 ++ fileServer/logger/logger.go | 53 ++++++++++++++++++++++++++++++ fileServer/main.go | 45 +++++++++++++++++++++++++ fileServer/server/server.go | 65 +++++++++++++++++++++++++++++++++++++ 6 files changed, 192 insertions(+) create mode 100644 fileServer/LICENSE create mode 100644 fileServer/README.md create mode 100644 fileServer/go.mod create mode 100644 fileServer/logger/logger.go create mode 100644 fileServer/main.go create mode 100644 fileServer/server/server.go diff --git a/fileServer/LICENSE b/fileServer/LICENSE new file mode 100644 index 0000000..a08fc5c --- /dev/null +++ b/fileServer/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright © 2021 Unbewohne | Nikolay Kasyanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/fileServer/README.md b/fileServer/README.md new file mode 100644 index 0000000..bbd3cc9 --- /dev/null +++ b/fileServer/README.md @@ -0,0 +1,17 @@ +# fileServer +## A simple implementaion of a simple local file server. Useful if you need to transport a file locally + +# Usage +## There are 2 flags you can specify +1. Port (`-port=`) - port that will be used by the server +2. Dir (`-dir=`) - the directory with its subdirectories that will be served + +## Examples +1. `./fileserver` - serve current directory (by default) on default port `8000` +2. `./fileserver -port=8080` - serve current directory on specified port `8080` +3. `./fileserver -dir="."` - serve current directory on default port `8000` +4. `./fileserver -dir=/` - serve "/" (root) on default port `8000` +5. `./fileserver -port=8080 -dir=/home/` - serve `/home/` on specified port `8080` + +# Note +## Hard-refresh the page in your browser (ctrl+F5) if you have changed the serving directory. Caching prevents you from seeing the changes \ No newline at end of file diff --git a/fileServer/go.mod b/fileServer/go.mod new file mode 100644 index 0000000..302668e --- /dev/null +++ b/fileServer/go.mod @@ -0,0 +1,3 @@ +module github.com/unbewohnte/Tiny-Utils/fileserver + +go 1.16 diff --git a/fileServer/logger/logger.go b/fileServer/logger/logger.go new file mode 100644 index 0000000..d44cb33 --- /dev/null +++ b/fileServer/logger/logger.go @@ -0,0 +1,53 @@ +package logger + +import ( + "log" + "os" + "path/filepath" +) + +var ( + infoLogger *log.Logger + warningLogger *log.Logger + errorLogger *log.Logger +) + +// creates directory for logs and sets output to file +func createLogsfile() *os.File { + logsDir := filepath.Join(".", "logs") + err := os.MkdirAll(logsDir, os.ModePerm) + if err != nil { + panic(err) + } + logfile, err := os.Create(filepath.Join(logsDir, "logs.log")) + log.SetOutput(logfile) + + return logfile +} + +// creates new custom loggers +func setUpLoggers(logfile *os.File) { + infoLogger = log.New(logfile, "INFO: ", log.Ldate|log.Ltime) + warningLogger = log.New(logfile, "WARNING: ", log.Ldate|log.Ltime) + errorLogger = log.New(logfile, "ERROR: ", log.Ldate|log.Ltime) +} + +func init() { + logfile := createLogsfile() + setUpLoggers(logfile) +} + +func LogInfo(message ...interface{}) { + infoLogger.Println(message...) +} + +func LogWarning(message ...interface{}) { + warningLogger.Println(message...) +} + +func LogError(isFatal bool, message ...interface{}) { + if isFatal { + errorLogger.Fatal(message...) + } + errorLogger.Println(message...) +} diff --git a/fileServer/main.go b/fileServer/main.go new file mode 100644 index 0000000..9c60838 --- /dev/null +++ b/fileServer/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/unbewohnte/Tiny-Utils/fileserver/logger" + "github.com/unbewohnte/Tiny-Utils/fileserver/server" +) + +var ( + PORT *int = flag.Int("port", 8000, "Specifies the port") + DIR *string = flag.String("dir", ".", "Specifies the directory that will be served") +) + +func init() { + flag.Parse() +} + +func main() { + fs := server.NewFileServer(uint(*PORT)) + + // check if directory does exist + _, err := os.Stat(*DIR) + if err != nil { + logger.LogError(true, "Given directory does not exist") + } + + fs.ServeDirectory("/", *DIR) + + logger.LogInfo("Created a new file server") + + localAddr, err := server.GetOutboundIP() + if err != nil { + logger.LogError(true, fmt.Sprintf("Could not retrieve your local IP address: %s", err)) + } + + logger.LogInfo(fmt.Sprintf("Serving \"%s\" at %s:%d", *DIR, localAddr.String(), *PORT)) + fmt.Println((fmt.Sprintf("Serving \"%s\" at %s:%d", *DIR, localAddr.String(), *PORT))) + err = fs.Start() + if err != nil { + logger.LogError(true, "Fatal server error: ", err) + } +} diff --git a/fileServer/server/server.go b/fileServer/server/server.go new file mode 100644 index 0000000..b0bd36a --- /dev/null +++ b/fileServer/server/server.go @@ -0,0 +1,65 @@ +package server + +import ( + "fmt" + "net" + "net/http" + "time" +) + +type FileServer struct { + server *http.Server + serveMux *http.ServeMux + Port uint + ServingLocation string +} + +func NewFileServer(port uint) *FileServer { + serveMux := http.NewServeMux() + + server := &http.Server{ + Addr: fmt.Sprintf(":%d", port), + Handler: serveMux, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + MaxHeaderBytes: 1 << 20, + } + return &FileServer{ + server: server, + serveMux: serveMux, + } +} + +// makes given directory and its subdirectories available +func (s *FileServer) ServeDirectory(pattern, dir string) { + s.serveMux.Handle(pattern, + http.StripPrefix(pattern, http.FileServer(http.Dir(dir)))) +} + +// makes available a certain file +func (s *FileServer) ServeFile(pattern, file string) { + s.serveMux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, file) + }) +} + +func (s *FileServer) Start() error { + err := s.server.ListenAndServe() + if err != nil { + return err + } + return nil +} + +// thanks to https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go +func GetOutboundIP() (net.IP, error) { + conn, err := net.Dial("udp", "8.8.8.8:80") + if err != nil { + return nil, err + } + defer conn.Close() + + localAddr := conn.LocalAddr().(*net.UDPAddr) + + return localAddr.IP, nil +}