Replaced %v with more specific format string in printf calls

This commit is contained in:
Seednode 2023-01-24 10:13:09 -06:00
parent fa5ae95cb3
commit da5bdfe765
4 changed files with 34 additions and 35 deletions

View File

@ -147,7 +147,7 @@ func imageDimensions(path string) (*Dimensions, error) {
func preparePath(path string) string { func preparePath(path string) string {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
path = fmt.Sprintf("/%v", filepath.ToSlash(path)) path = fmt.Sprintf("/%s", filepath.ToSlash(path))
} }
return path return path
@ -320,7 +320,7 @@ func tryExtensions(p *Path) (string, error) {
var fileName string var fileName string
for _, extension := range extensions { for _, extension := range extensions {
fileName = fmt.Sprintf("%v%.3d%v", p.base, p.number, extension) fileName = fmt.Sprintf("%s%.3d%s", p.base, p.number, extension)
exists, err := fileExists(fileName) exists, err := fileExists(fileName)
if err != nil { if err != nil {
@ -358,7 +358,7 @@ func pathIsValid(filePath string, paths []string) bool {
switch { switch {
case Verbose && !matchesPrefix: case Verbose && !matchesPrefix:
fmt.Printf("%v | Error: Failed to serve file outside specified path(s): %v\n", fmt.Printf("%s | Error: Failed to serve file outside specified path(s): %s\n",
time.Now().Format(logDate), time.Now().Format(logDate),
filePath, filePath,
) )
@ -478,7 +478,7 @@ func fileList(paths []string, filters *Filters, sort string, index *Index) ([]st
fileList = prepareDirectories(files, sort) fileList = prepareDirectories(files, sort)
if Verbose { if Verbose {
fmt.Printf("%v | Indexed %v/%v files across %v directories in %v\n", fmt.Printf("%s | Indexed %d/%d files across %d directories in %s\n",
time.Now().Format(logDate), time.Now().Format(logDate),
stats.FilesMatched(), stats.FilesMatched(),
stats.FilesTotal(), stats.FilesTotal(),
@ -591,9 +591,9 @@ func normalizePaths(args []string) ([]string, error) {
} }
if (args[i]) != absolutePath { if (args[i]) != absolutePath {
fmt.Printf("%v (resolved to %v)\n", args[i], absolutePath) fmt.Printf("%s (resolved to %s)\n", args[i], absolutePath)
} else { } else {
fmt.Printf("%v\n", args[i]) fmt.Printf("%s\n", args[i])
} }
paths = append(paths, absolutePath) paths = append(paths, absolutePath)

View File

@ -5,7 +5,7 @@ Copyright © 2023 Seednode <seednode@seedno.de>
package cmd package cmd
import ( import (
"log" "fmt"
"os" "os"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -39,7 +39,8 @@ var rootCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
err := ServePage(args) err := ServePage(args)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
os.Exit(1)
} }
}, },
} }
@ -47,6 +48,7 @@ var rootCmd = &cobra.Command{
func Execute() { func Execute() {
err := rootCmd.Execute() err := rootCmd.Execute()
if err != nil { if err != nil {
fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
} }

View File

@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var Version = "0.34.0" var Version = "0.34.1"
func init() { func init() {
rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(versionCmd)

View File

@ -8,7 +8,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log"
"math/rand" "math/rand"
"net/http" "net/http"
"net/url" "net/url"
@ -160,7 +159,7 @@ func notFound(w http.ResponseWriter, r *http.Request, filePath string) error {
startTime := time.Now() startTime := time.Now()
if Verbose { if Verbose {
fmt.Printf("%v | Unavailable file %v requested by %v\n", fmt.Printf("%s | Unavailable file %s requested by %s\n",
startTime.Format(logDate), startTime.Format(logDate),
filePath, filePath,
r.RemoteAddr, r.RemoteAddr,
@ -196,9 +195,7 @@ func refreshInterval(r *http.Request, regexes *Regexes) (int64, string) {
return 0, "0ms" return 0, "0ms"
} }
durationInMs := duration.Milliseconds() return duration.Milliseconds(), refreshInterval
return durationInMs, refreshInterval
} }
func sortOrder(r *http.Request) string { func sortOrder(r *http.Request) string {
@ -254,7 +251,7 @@ func generateQueryParams(filters *Filters, sortOrder, refreshInterval string) st
queryParams.WriteString("&") queryParams.WriteString("&")
} }
queryParams.WriteString(fmt.Sprintf("sort=%v", sortOrder)) queryParams.WriteString(fmt.Sprintf("sort=%s", sortOrder))
hasParams = true hasParams = true
} }
@ -262,7 +259,7 @@ func generateQueryParams(filters *Filters, sortOrder, refreshInterval string) st
if hasParams { if hasParams {
queryParams.WriteString("&") queryParams.WriteString("&")
} }
queryParams.WriteString(fmt.Sprintf("refresh=%v", refreshInterval)) queryParams.WriteString(fmt.Sprintf("refresh=%s", refreshInterval))
return queryParams.String() return queryParams.String()
} }
@ -319,13 +316,13 @@ func realIP(r *http.Request) string {
remotePort := remoteAddr[len(remoteAddr)-1] remotePort := remoteAddr[len(remoteAddr)-1]
cfIP := r.Header.Get("Cf-Connecting-Ip") cfIP := r.Header.Get("Cf-Connecting-Ip")
xRealIp := r.Header.Get("X-Real-Ip") xRealIP := r.Header.Get("X-Real-Ip")
switch { switch {
case cfIP != "": case cfIP != "":
return cfIP + ":" + remotePort return cfIP + ":" + remotePort
case xRealIp != "": case xRealIP != "":
return xRealIp + ":" + remotePort return xRealIP + ":" + remotePort
default: default:
return r.RemoteAddr return r.RemoteAddr
} }
@ -348,17 +345,17 @@ func html(w http.ResponseWriter, r *http.Request, filePath string, dimensions *D
htmlBody.WriteString(`a{display:block;height:100%;width:100%;text-decoration:none;}`) htmlBody.WriteString(`a{display:block;height:100%;width:100%;text-decoration:none;}`)
htmlBody.WriteString(`img{margin:auto;display:block;max-width:97%;max-height:97%;object-fit:scale-down;`) htmlBody.WriteString(`img{margin:auto;display:block;max-width:97%;max-height:97%;object-fit:scale-down;`)
htmlBody.WriteString(`position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}</style>`) htmlBody.WriteString(`position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}</style>`)
htmlBody.WriteString(fmt.Sprintf(`<title>%v (%vx%v)</title>`, htmlBody.WriteString(fmt.Sprintf(`<title>%s (%dx%d)</title>`,
fileName, fileName,
dimensions.width, dimensions.width,
dimensions.height)) dimensions.height))
htmlBody.WriteString(`</head><body>`) htmlBody.WriteString(`</head><body>`)
if refreshInterval != "0ms" { if refreshInterval != "0ms" {
htmlBody.WriteString(fmt.Sprintf("<script>window.onload = function(){setInterval(function(){window.location.href = '/%v';}, %v);};</script>", htmlBody.WriteString(fmt.Sprintf("<script>window.onload = function(){setInterval(function(){window.location.href = '/%s';}, %d);};</script>",
queryParams, queryParams,
refreshTimer)) refreshTimer))
} }
htmlBody.WriteString(fmt.Sprintf(`<a href="/%v"><img src="%v" width="%v" height="%v" alt="Roulette selected: %v"></a>`, htmlBody.WriteString(fmt.Sprintf(`<a href="/%s"><img src="%s" width="%d" height="%d" alt="Roulette selected: %s"></a>`,
queryParams, queryParams,
generateFilePath(filePath), generateFilePath(filePath),
dimensions.width, dimensions.width,
@ -414,7 +411,7 @@ func staticFile(w http.ResponseWriter, r *http.Request, paths []string, stats *S
fileSize := humanReadableSize(len(buf)) fileSize := humanReadableSize(len(buf))
if Verbose { if Verbose {
fmt.Printf("%v | Served %v (%v) to %v in %v\n", fmt.Printf("%s | Served %s (%s) to %s in %s\n",
startTime.Format(logDate), startTime.Format(logDate),
filePath, filePath,
fileSize, fileSize,
@ -447,13 +444,13 @@ func statsHandler(args []string, stats *ServeStats) http.HandlerFunc {
response, err := stats.ListImages() response, err := stats.ListImages()
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
w.Write(response) w.Write(response)
if Verbose { if Verbose {
fmt.Printf("%v | Served statistics page (%v) to %v in %v\n", fmt.Printf("%s | Served statistics page (%s) to %s in %s\n",
startTime.Format(logDate), startTime.Format(logDate),
humanReadableSize(len(response)), humanReadableSize(len(response)),
realIP(r), realIP(r),
@ -467,7 +464,7 @@ func staticFileHandler(paths []string, stats *ServeStats) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
err := staticFile(w, r, paths, stats) err := staticFile(w, r, paths, stats)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
} }
} }
@ -476,7 +473,7 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
refererUri, err := stripQueryParams(refererToUri(r.Referer())) refererUri, err := stripQueryParams(refererToUri(r.Referer()))
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
filters := &Filters{ filters := &Filters{
@ -495,7 +492,7 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
if refererUri != "" { if refererUri != "" {
filePath, err = nextFile(refererUri, sortOrder, regexes) filePath, err = nextFile(refererUri, sortOrder, regexes)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
} }
@ -507,13 +504,13 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
return return
case err != nil: case err != nil:
log.Fatal(err) fmt.Println(err)
} }
} }
queryParams := generateQueryParams(filters, sortOrder, refreshInterval) queryParams := generateQueryParams(filters, sortOrder, refreshInterval)
newUrl := fmt.Sprintf("http://%v%v%v", newUrl := fmt.Sprintf("http://%s%s%s",
r.Host, r.Host,
preparePath(filePath), preparePath(filePath),
queryParams, queryParams,
@ -528,7 +525,7 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
exists, err := fileExists(filePath) exists, err := fileExists(filePath)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
if !exists { if !exists {
notFound(w, r, filePath) notFound(w, r, filePath)
@ -538,7 +535,7 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
image, err := isImage(filePath) image, err := isImage(filePath)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
if !image { if !image {
notFound(w, r, filePath) notFound(w, r, filePath)
@ -548,12 +545,12 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
dimensions, err := imageDimensions(filePath) dimensions, err := imageDimensions(filePath)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
err = html(w, r, filePath, dimensions, filters, regexes) err = html(w, r, filePath, dimensions, filters, regexes)
if err != nil { if err != nil {
log.Fatal(err) fmt.Println(err)
} }
} }
} }
@ -562,7 +559,7 @@ func htmlHandler(paths []string, regexes *Regexes, index *Index) http.HandlerFun
func doNothing(http.ResponseWriter, *http.Request) {} func doNothing(http.ResponseWriter, *http.Request) {}
func ServePage(args []string) error { func ServePage(args []string) error {
fmt.Printf("roulette v%v\n\n", Version) fmt.Printf("roulette v%s\n\n", Version)
paths, err := normalizePaths(args) paths, err := normalizePaths(args)
if err != nil { if err != nil {