Compare commits

...

2 commits

Author SHA1 Message Date
=
aa8bda8622 an epic code formatting commit 2025-03-14 07:15:55 -04:00
=
881619dfac refactored code, added HTML template for rich embeds 2025-03-14 07:14:33 -04:00

174
main.go
View file

@ -1,5 +1,4 @@
package main
import (
"crypto/rand"
"encoding/hex"
@ -15,10 +14,8 @@ import (
"path/filepath"
"strings"
"time"
"github.com/msteinert/pam"
)
type Config struct {
Listen string
StorageDir string
@ -28,9 +25,17 @@ type Config struct {
IndexHTML string
}
var config Config
type ImagePageData struct {
Title string
ImageURL string
BaseURL string
Description string
FullImageURL string
}
var config Config
var indexHTML string
var imagePageTemplate string
func loadIndexHTML() {
content, err := os.ReadFile(config.IndexHTML)
@ -38,6 +43,67 @@ func loadIndexHTML() {
panic(err)
}
indexHTML = string(content)
// HTML template for rendering images
imagePageTemplate = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#6BABDA">
<title>{{.Title}}</title>
<!-- Open Graph meta tags -->
<meta property="og:title" content="{{.Title}}">
<meta property="og:type" content="image">
<meta property="og:image" content="{{.FullImageURL}}">
<meta property="og:url" content="{{.FullImageURL}}">
<meta property="og:description" content="{{.Description}}">
<!-- Twitter Card meta tags for better image display -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{{.Title}}">
<meta name="twitter:description" content="{{.Description}}">
<meta name="twitter:image" content="{{.FullImageURL}}">
<style>
body {
font-family: monospace;
margin: 0;
padding: 20px;
text-align: center;
background-color: #111111;
color: #6BABDA;
}
img {
max-width: 100%;
height: auto;
border: 1px solid #6babda;
padding: 5px;
}
.container {
max-width: 90%;
margin: 0 auto;
}
a {
color: #8CC7E7;
text-decoration: none;
border-bottom: 1px dotted #8CC7E7;
}
a:hover {
border-bottom: 1px solid #8CC7E7;
}
</style>
</head>
<body>
<div class="container">
<h1>{{.Title}}</h1>
<img src="{{.ImageURL}}?raw=true" alt="{{.Title}}"><br>
<a href="{{.ImageURL}}?download=true">Download Image</a>
</div>
</body>
</html>`
}
func init() {
@ -91,24 +157,48 @@ func cleanupOldFiles() {
}
}
func isImageFile(filePath string) bool {
file, err := os.Open(filePath)
if err != nil {
log.Printf("Error opening file for MIME detection: %v", err)
return false
}
defer file.Close()
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil && err != io.EOF {
log.Printf("Error reading file for MIME detection: %v", err)
return false
}
_, err = file.Seek(0, 0)
if err != nil {
log.Printf("Error seeking file after MIME detection: %v", err)
return false
}
contentType := http.DetectContentType(buffer)
log.Printf("Detected content type for %s: %s", filePath, contentType)
return strings.HasPrefix(contentType, "image/")
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
username, password, ok := r.BasicAuth()
if !ok || !authenticateUser(username, password) {
w.Header().Set("WWW-Authenticate", `Basic realm="Upload"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if r.ContentLength > config.MaxFileSize {
http.Error(w, "File too large", http.StatusRequestEntityTooLarge)
return
}
ext := path.Ext(r.URL.Path)
if ext == "" {
contentType := r.Header.Get("Content-Type")
@ -117,62 +207,102 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
ext = exts[0]
}
}
randomName, err := generateRandomFilename()
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
filename := randomName + ext
filepath := path.Join(config.StorageDir, filename)
f, err := os.Create(filepath)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
defer f.Close()
_, err = io.Copy(f, r.Body)
if err != nil {
os.Remove(filepath)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
fileURL := strings.TrimRight(config.BaseURL, "/") + "/" + filename
fmt.Fprintf(w, "%s\n", fileURL)
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.ServeFile(w, r, path.Join(config.StorageDir, r.URL.Path))
return
}
if r.URL.Path == "/" {
tmpl, err := template.New("index").Parse(indexHTML)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
tmpl.Execute(w, config)
return
}
requestPath := strings.TrimPrefix(r.URL.Path, "/")
filePath := path.Join(config.StorageDir, requestPath)
log.Printf("Requested path: %s, File path: %s", r.URL.Path, filePath)
fileInfo, err := os.Stat(filePath)
if err != nil {
log.Printf("File not found: %s, Error: %v", filePath, err)
http.NotFound(w, r)
return
}
if r.URL.Query().Get("raw") == "true" || r.URL.Query().Get("download") == "true" {
if r.URL.Query().Get("download") == "true" {
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(requestPath)))
}
log.Printf("Serving file directly: %s", filePath)
http.ServeFile(w, r, filePath)
return
}
if !isImageFile(filePath) {
log.Printf("File is not an image, serving directly: %s", filePath)
http.ServeFile(w, r, filePath)
return
}
tmpl, err := template.New("imagePage").Parse(imagePageTemplate)
if err != nil {
log.Printf("Template parsing error: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
baseURL := strings.TrimRight(config.BaseURL, "/")
data := ImagePageData{
Title: "Filename: " + filepath.Base(requestPath),
ImageURL: r.URL.Path, // Use the original request path for the image URL
BaseURL: baseURL,
Description: fmt.Sprintf("Image shared on %s, size: %d bytes", fileInfo.ModTime().Format("Jan 2, 2006"), fileInfo.Size()),
FullImageURL: baseURL + r.URL.Path + "?raw=true", // Full URL for the image with raw parameter
}
log.Printf("Serving image template with data: %+v", data)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, data)
}
func main() {
flag.Parse()
loadIndexHTML()
if err := os.MkdirAll(config.StorageDir, 0700); err != nil {
log.Fatalf("Failed to create storage directory: %v", err)
}
go cleanupOldFiles()
http.HandleFunc("/", handleIndex)
http.HandleFunc("/upload", handleUpload)
log.Printf("Starting server on %s", config.Listen)
log.Printf("Storage directory: %s", config.StorageDir)
log.Printf("Base URL: %s", config.BaseURL)
log.Fatal(http.ListenAndServe(config.Listen, nil))
}