/* The MIT License (MIT) Copyright © 2025 pacman64 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. */ /* To compile a smaller-sized command-line app, you can use the `go` command as follows: go build -ldflags "-s -w" -trimpath si.go */ package main import ( "bufio" "bytes" "encoding/base64" "errors" "io" "net" "os" "os/exec" "path/filepath" "runtime" "strings" ) const info = ` si [options...] [filenames/URIs...] This app (Show It) shows data using your default web browser by auto-opening tabs. When reading from stdin, the content-type is auto-detected: data are then sent right away to the browser via localhost, using a random port among the available ones. The localhost connection is available only until all data are transferred: this means refreshing your browser tab will lose your content, replacing it with a server-not-found message page. When given filenames and/or URIs, the browser tabs will point to their paths, so accidentally reloading them doesn't make their content disappear, unless those files are actually deleted between reloads. Dozens of common data-formats are recognized when piped from stdin, such as - HTML (web pages) - PDF - pictures (PNG, JPEG, SVG, WEBP, GIF) - audio (AAC, MP3, FLAC, WAV, AU, MIDI) - video (MP4, MOV, WEBM, MKV, AVI) - JSON - generic UTF-8 plain-text Base64-encoded data URIs are auto-detected and decoded appropriately. The options are, available both in single and double-dash versions -h show this help message -help show this help message -from declare MIME type, instead of auto-guessing it -mime declare MIME type, instead of auto-guessing it -play autoplay media; useful only for audio/video data -autoplay autoplay media; useful only for audio/video data ` func main() { args := os.Args[1:] var cfg config for len(args) > 0 { if args[0] == `--` { args = args[1:] break } if hasAnyPrefix(args[0], `-from=`, `--from=`, `-mime=`, `--mime=`) { cfg.From = args[0][strings.IndexByte(args[0], '=')+1:] args = args[1:] continue } switch args[0] { case `-h`, `--h`, `-help`, `--help`: os.Stdout.WriteString(info[1:]) return case `-autoplay`, `--autoplay`, `-play`, `--play`: cfg.Autoplay = true args = args[1:] case `-from`, `--from`, `-mime`, `--mime`: if len(args) == 0 { os.Stderr.WriteString("missing MIME-type argument\n") os.Exit(1) } cfg.From = args[1] args = args[2:] } } nerr := 0 // show all filenames/URIs given by opening new browser tabs for each for _, s := range args { s = strings.TrimSpace(s) if err := handle(s, cfg); err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") nerr++ } } // serve from stdin only if no filenames were given if len(args) == 0 { if err := handleInput(os.Stdin, cfg); err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") nerr++ } } // quit in failure if any input clearly failed to show up if nerr > 0 { os.Exit(1) } } func hasAnyPrefix(s string, prefixes ...string) bool { for _, p := range prefixes { if strings.HasPrefix(s, p) { return true } } return false } // handle shows a filename/URI by operning a new browser tab for it func handle(s string, cfg config) error { // open a new browser window for each URI if strings.HasPrefix(s, `https://`) || strings.HasPrefix(s, `http://`) { return showURI(s) } // handle data-URIs if strings.HasPrefix(s, `data:`) && strings.Contains(s, `;base64,`) { if err := showURI(s); err != nil { return err } return handleInput(strings.NewReader(s), cfg) } // the browser needs full paths when showing local files fpath, err := filepath.Abs(s) if err != nil { return err } // open a new browser tab for each full-path filename return showURI(`file:///` + fpath) } // showURI tries to open the file/url given using the host operating system's // defaults func showURI(what string) error { const fph = `url.dll,FileProtocolHandler` switch runtime.GOOS { case `windows`: return exec.Command(`rundll32`, fph, what).Run() case `darwin`: return exec.Command(`open`, what).Run() default: return exec.Command(`xdg-open`, what).Run() } } // handleInput specifically handles stdin and data-URIs func handleInput(r io.Reader, cfg config) error { if cfg.From != `` { return serveOnce(nil, r, serveConfig{ ContentType: cfg.From, ContentLength: -1, Autoplay: cfg.Autoplay, }) } // before starting the single-request server, try to detect the MIME type // by inspecting the first bytes of the stream and matching known filetype // starting patterns var buf [64]byte n, err := r.Read(buf[:]) if err != nil && err != io.EOF { return err } start := buf[:n] // handle data-URI-like inputs if bytes.HasPrefix(start, []byte(`data:`)) { if bytes.Contains(start, []byte(`;base64,`)) { return handleDataURI(start, r, cfg) } } // handle regular data, trying to auto-detect its MIME type using // its first few bytes mime, ok := detectMIME(start) if !ok { mime = cfg.From } if mime == `` { mime = `text/plain` } // remember to precede the partly-used reader with the starting bytes; // give a negative/invalid filesize hint, since stream is single-use return serveOnce(start, r, serveConfig{ ContentType: mime, ContentLength: -1, Autoplay: cfg.Autoplay, }) } // handleDataURI handles data-URIs for func handleInput func handleDataURI(start []byte, r io.Reader, cfg config) error { if !bytes.HasPrefix(start, []byte(`data:`)) { return errors.New(`invalid data-URI`) } i := bytes.Index(start, []byte(`;base64,`)) if i < 0 { return errors.New(`invalid data-URI`) } // force browser to play wave and aiff sounds, instead of // showing a useless download-file option switch mime := string(start[len(`data:`):i]); mime { case `audio/wav`, `audio/wave`, `audio/x-wav`, `audio/aiff`, `audio/x-aiff`: before := beforeAudio if cfg.Autoplay { before = beforeAutoplayAudio } // surround URI-encoded audio data with a web page only having // a media player in it: this is necessary for wave and aiff // sounds, since web browsers may insist on a useless download // option for those media types r = io.MultiReader( strings.NewReader(before), bytes.NewReader(start), r, strings.NewReader(afterAudio), ) return serveOnce(nil, r, serveConfig{ ContentType: `text/html; charset=UTF-8`, ContentLength: -1, Autoplay: cfg.Autoplay, }) case `image/bmp`, `image/x-bmp`: // surround URI-encoded bitmap data with a web page only having // an image element in it: this is necessary for bitmap pictures, // since web browsers may insist on a useless download option for // that media type r = io.MultiReader( strings.NewReader(beforeBitmap), bytes.NewReader(start), r, strings.NewReader(afterBitmap), ) return serveOnce(nil, r, serveConfig{ ContentType: `text/html; charset=UTF-8`, ContentLength: -1, Autoplay: cfg.Autoplay, }) default: start = start[i+len(`;base64,`):] r = io.MultiReader(bytes.NewReader(start), r) dec := base64.NewDecoder(base64.URLEncoding, r) // give a negative/invalid filesize hint, since stream is single-use return serveOnce(nil, dec, serveConfig{ ContentType: mime, ContentLength: -1, Autoplay: cfg.Autoplay, }) } } // config is the result of parsing all cmd-line arguments the app was given type config struct { // From is an optional hint for the source data format, and disables // type-autodetection when it's non-empty From string // Autoplay autoplays audio/video data from stdin Autoplay bool } const ( fromUsage = `` + `declare MIME-type, disabling type-autodetection; ` + `use when MIME-type autodetection fails, or to use a ` + `charset different from UTF-8` mimeUsage = `alias for option -from` playUsage = `alias for option -autoplay` autoplayUsage = `autoplay; useful only when stdin has audio/video data` ) // serveConfig has all details func serveOnce needs type serveConfig struct { // ContentType is the MIME type of what's being served ContentType string // ContentLength is the byte-count of what's being served; negative // values are ignored ContentLength int // Autoplay autoplays audio/video data from stdin Autoplay bool } // makeDotless is similar to filepath.Ext, except its results never start // with a dot func makeDotless(s string) string { i := strings.LastIndexByte(s, '.') if i >= 0 { return s[(i + 1):] } return s } // hasPrefixByte is a simpler, single-byte version of bytes.HasPrefix func hasPrefixByte(b []byte, prefix byte) bool { return len(b) > 0 && b[0] == prefix } // hasPrefixFold is a case-insensitive bytes.HasPrefix func hasPrefixFold(s []byte, prefix []byte) bool { n := len(prefix) return len(s) >= n && bytes.EqualFold(s[:n], prefix) } // trimLeadingWhitespace ignores leading space-like symbols: this is useful // to handle text-based data formats more flexibly func trimLeadingWhitespace(b []byte) []byte { for len(b) > 0 { switch b[0] { case ' ', '\t', '\n', '\r': b = b[1:] default: return b } } // an empty slice is all that's left, at this point return nil } const ( // maxbufsize is the max capacity the HTTP-protocol line-scanners are // allowed to reach maxbufsize = 128 * 1024 // beforeAudio starts HTML webpage with just an audio player beforeAudio = ` wave sound