File: serve.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright (c) 2026 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the "Software"), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath serve.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "errors"
  36     "fmt"
  37     "net/http"
  38     "os"
  39     "path"
  40     "strconv"
  41     "strings"
  42 )
  43 
  44 const info = `
  45 serve [port] [file/folder...]
  46 
  47 Web-serve any file in a folder (or just a file) via HTTP, using the port given.
  48 `
  49 
  50 func main() {
  51     if len(os.Args) > 1 {
  52         switch os.Args[1] {
  53         case `-h`, `--h`, `-help`, `--help`:
  54             os.Stdout.WriteString(info[1:])
  55             return
  56         }
  57     }
  58 
  59     port, what, err := parseArgs(os.Args[1:])
  60     if err != nil {
  61         showError(err)
  62         os.Exit(1)
  63     }
  64     if !strings.HasPrefix(port, `:`) {
  65         port = `:` + port
  66     }
  67 
  68     info, err := os.Stat(what)
  69     if err != nil {
  70         showError(err)
  71         os.Exit(1)
  72     }
  73 
  74     fmt.Fprintf(os.Stderr, "serving %s via HTTP on port %s\n", what, port)
  75 
  76     what = path.Clean(what)
  77     serve := serveFolder
  78     if !info.IsDir() {
  79         serve = serveFile
  80     }
  81 
  82     if err := serve(port, what); err != nil {
  83         showError(err)
  84         os.Exit(1)
  85     }
  86 }
  87 
  88 func showError(err error) {
  89     os.Stderr.WriteString(err.Error())
  90     os.Stderr.WriteString("\n")
  91 }
  92 
  93 func parseArgs(args []string) (port string, path string, err error) {
  94     if len(args) == 0 || len(args) > 2 {
  95         return ``, ``, errors.New(info[1:])
  96     }
  97 
  98     if isValidPort(args[0]) {
  99         port = args[0]
 100         if len(args) == 2 {
 101             path = args[1]
 102         }
 103         return port, path, nil
 104     }
 105 
 106     if len(args) == 2 && isValidPort(args[1]) {
 107         path = args[0]
 108         port = args[1]
 109         return port, path, nil
 110     }
 111 
 112     return ``, ``, errors.New(`not given a port number to serve from`)
 113 }
 114 
 115 func isValidPort(s string) bool {
 116     if strings.HasPrefix(s, `:`) {
 117         s = s[1:]
 118     }
 119 
 120     n, err := strconv.Atoi(s)
 121     if err != nil {
 122         return false
 123     }
 124     return 1 <= n && n <= 65_535
 125 }
 126 
 127 func serveFile(port string, file string) error {
 128     http.HandleFunc(`/`, func(w http.ResponseWriter, r *http.Request) {
 129         http.ServeFile(w, r, file)
 130     })
 131     return http.ListenAndServe(port, nil)
 132 }
 133 
 134 func serveFolder(port string, path string) error {
 135     http.Handle(`/`, http.FileServer(http.Dir(path)))
 136     return http.ListenAndServe(port, nil)
 137 }