From d0cfd2c0610bb6465457ca62da747795c9511adb Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Thu, 26 Oct 2023 17:13:04 +0300 Subject: [PATCH] feat: go rewrite --- index.js | 198 --------------------------------------------------- main.go | 83 +++++++++++++++++++++ package.json | 17 ----- 3 files changed, 83 insertions(+), 215 deletions(-) delete mode 100644 index.js create mode 100644 main.go delete mode 100644 package.json diff --git a/index.js b/index.js deleted file mode 100644 index 0acbd92..0000000 --- a/index.js +++ /dev/null @@ -1,198 +0,0 @@ - -const express = require('express'); -const app = express(); -const fs = require('fs'); -require('dotenv').config(); - -// Use tycrek's logging library for fancy messages -// also configure the timestamps so they don't appear -// timestamps look ugly -const TLog = require('@tycrek/log') -const logger2 = new TLog({ - timestamp: { - enabled: false - } -}); - -// Check if a custom port is set in .env -// if it is, then check if a custom url is defined. Paste the correct IP:port combo or the custom url. -// You will need to handle domain -> raw IP redirection yourself. -if(process.env.PORT) { - const port = process.env.PORT; // Set port variable to the value in .env - logger2 - .success('Custom port is set. Using custom port ' + port) - app.listen(port, () => { - if(process.env.CUSTOMURL) { // Check if customURL is defined .env - const customurl = process.env.CUSTOMURL; // if it is, set customurl variable to the value in .env - logger2 // alternative to console.lgg because looks better leave me alone - .success('Custom URL defined as ' + customurl) - .info('App listening at ' + 'https://' + customurl) - .comment('Godspeed, little fella!') - const getRandomImageApi = () => { - const path = getRandomImagePath(); - const id = path.substring(0, path.length - 4).split('-')[1]; - return { - id: parseInt(id), - url: 'https://' + customurl + '/' + id, - }; - } - - app.get('/api/random', (req, res) => { - return res.json(getRandomImageApi()); - }); - - app.get('/api/:id', (req, res) => { - const image = getImageById(req.params.id, false); - - if (image) { - return res.json({ - id: parseInt(req.params.id), - url: 'https://' + customurl + '/' + req.params.id, - }); - - } - else { - return res.json({ - error: 'Image not found' - }); - } - }); - - } - else { - logger2 - .error('Custom URL not defined. Falling back to localhost') - .info('App listening at http://localhost:' + port) - .comment('Godspeed, little fella!') - const getRandomImageApi = () => { - const path = getRandomImagePath(); - const id = path.substring(0, path.length - 4).split('-')[1]; - return { - id: parseInt(id), - url: 'http://localhost:' + port + '/' + id, - }; - } - app.get('/api/random', (req, res) => { - return res.json(getRandomImageApi()); - }); - app.get('/api/:id', (req, res) => { - const image = getImageById(req.params.id, false); - if (image) { - return res.json({ - id: parseInt(req.params.id), - url: 'http://localhost:' + port + '/' + req.params.id, - }); - } else { - return res.json({ - error: 'Image not found' - }); - } - }); - - } - }); -} - -else { - const port = 3005; - logger2 - .error('Custom port is not set. Falling back to port ' + port); - app.listen(port, () => { - if(process.env.CUSTOMURL) { - logger2 - .success('Custom URL defined. Using custom url ' + customurl) - .success('App listening at ' + 'https://' + customurl); - console.log('Godspeed, little fella!'); - const getRandomImageApi = () => { - const path = getRandomImagePath(); - const id = path.substring(0, path.length - 4).split('-')[1]; - return { - id: parseInt(id), - url: 'http://' + customurl + '/' + id, - }; - } - app.get('/api/random', (req, res) => { - return res.json(getRandomImageApi()); - }); - - } - else { - logger2 - .error('Custom URL not defined. Falling back to localhost') - .info('App listening at ' + 'http://localhost:' + port) - .comment('Godspeed, little fella!') - const getRandomImageApi = () => { - const path = getRandomImagePath(); - const id = path.substring(0, path.length - 4).split('-')[1]; - return { - id: parseInt(id), - url: 'http://localhost:' + port + '/' + id, - }; - } - - app.get('/api/random', (req, res) => { - return res.json(getRandomImageApi()); - }); - - } - }); -} - -app.get('/', (req, res) => { - res.sendFile(getRandomImagePath(), (err) => { - if (err) { - res.status(err.status).end(); - } - }); -}); - -app.get('/:id', (req, res) => { - const image = getImageById(req.params.id); - if (image) { - res.sendFile(image, (err) => { - if (err) { - res.status(err.status).end(); - } - }); - } else { - return res.json({ - error: 'Image not found' - }); - } -}); - -app.get('/api/list', (req, res) => { - return res.json(getAllImageIds()); -}); - - -const getRandomImagePath = () => { - const images = fs.readdirSync('./images'); - return __dirname + '/images/' + images[Math.floor(Math.random() * images.length)]; -}; - -const getImageById = (id, path = true) => { - const images = fs.readdirSync('./images'); - - for (const image of images) { - if (image.substring(0, image.length - 4).split('-')[1] === id) { - if (path) { - return __dirname + '/images/' + image; - } else { - return image; - } - } - } - - return null; -}; - -const getAllImageIds = () => { - const ids = []; - - fs.readdirSync('./images').forEach(image => { - ids.push(parseInt(image.substring(0, image.length - 4) .split('-')[1])); - }); - - return ids.sort((a, b) => a - b); -}; diff --git a/main.go b/main.go new file mode 100644 index 0000000..03ae6dc --- /dev/null +++ b/main.go @@ -0,0 +1,83 @@ +package main + +import ( + "fmt" + "log" + "math/rand" + "net/http" + "os" + "strconv" + "strings" + "time" +) + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "3005" + } + + fs := http.FileServer(http.Dir("./static")) + http.Handle("/static/", http.StripPrefix("/static/", fs)) + + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + path := getRandomImagePath() + http.ServeFile(w, r, path) + }) + + http.HandleFunc("/api/random", func(w http.ResponseWriter, r *http.Request) { + path := getRandomImagePath() + id := strings.Split(path, "-")[1][:len(path)-5] + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"id":` + id + `, "url":"http://localhost:` + port + `/` + id + `"}`)) + }) + + http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) { + id := strings.TrimPrefix(r.URL.Path, "/api/") + path := getImageById(id) + if path != "" { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"id":` + id + `, "url":"http://localhost:` + port + `/` + id + `"}`)) + } else { + w.WriteHeader(http.StatusNotFound) + w.Write([]byte(`{"error": "Image not found"}`)) + } + }) + + http.HandleFunc("/api/list", func(w http.ResponseWriter, r *http.Request) { + ids := getAllImageIds() + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`[` + strings.Trim(strings.Join(strings.Split(strings.Trim(fmt.Sprint(ids), "[]"), " "), ","), ",") + `]`)) + }) + + log.Println("Listening on port", port) + log.Fatal(http.ListenAndServe(":"+port, nil)) +} + +func getRandomImagePath() string { + files, _ := os.ReadDir("./images") + rand.Seed(time.Now().UnixNano()) + randomIndex := rand.Intn(len(files)) + return "./images/" + files[randomIndex].Name() +} + +func getImageById(id string) string { + files, _ := os.ReadDir("./images") + for _, file := range files { + if strings.HasPrefix(file.Name(), id) { + return "./images/" + file.Name() + } + } + return "" +} + +func getAllImageIds() []int { + files, _ := os.ReadDir("./images") + ids := make([]int, 0, len(files)) + for _, file := range files { + id := strings.Split(file.Name(), "-")[1][:len(file.Name())-5] + idInt, _ := strconv.Atoi(id) + ids = append(ids, idInt) + } + return ids +} diff --git a/package.json b/package.json deleted file mode 100644 index 1bb983a..0000000 --- a/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "catapi", - "version": "1.1.0", - "description": "", - "main": "index.js", - "scripts": { - "start": "node index.js" - }, - "keywords": [], - "author": "NotAShelf", - "license": "MIT", - "dependencies": { - "@tycrek/log": "^0.5.9", - "dotenv": "^14.2.0", - "express": "^4.17.1" - } -}