feat: go rewrite

This commit is contained in:
raf 2023-10-26 17:13:04 +03:00
parent 7aeae4cd61
commit d0cfd2c061
No known key found for this signature in database
GPG key ID: 02D1DD3FA08B6B29
3 changed files with 83 additions and 215 deletions

198
index.js
View file

@ -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);
};

83
main.go Normal file
View file

@ -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
}

View file

@ -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"
}
}