File: serve.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2020-2025 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 Single-file source-code for serve.
  27 
  28 To compile a smaller-sized command-line app, you can use the `go` command as
  29 follows:
  30 
  31 go build -ldflags "-s -w" -trimpath serve.go
  32 */
  33 
  34 package main
  35 
  36 import (
  37     "errors"
  38     "fmt"
  39     "net/http"
  40     "os"
  41     "path"
  42     "strconv"
  43     "strings"
  44 )
  45 
  46 const info = `
  47 serve [port] [file/folder...]
  48 
  49 Web-serve any file in a folder (or just a file) via HTTP, using the port given.
  50 `
  51 
  52 func main() {
  53     if len(os.Args) > 1 {
  54         switch os.Args[1] {
  55         case `-h`, `--h`, `-help`, `--help`:
  56             os.Stderr.WriteString(info[1:])
  57             return
  58         }
  59     }
  60 
  61     port, what, err := parseArgs(os.Args[1:])
  62     if err != nil {
  63         showError(err)
  64         os.Exit(1)
  65     }
  66     if !strings.HasPrefix(port, `:`) {
  67         port = `:` + port
  68     }
  69 
  70     info, err := os.Stat(what)
  71     if err != nil {
  72         showError(err)
  73         os.Exit(1)
  74     }
  75 
  76     fmt.Fprintf(os.Stderr, "serving %s via HTTP on port %s\n", what, port)
  77 
  78     what = path.Clean(what)
  79     serve := serveFolder
  80     if !info.IsDir() {
  81         serve = serveFile
  82     }
  83 
  84     if err := serve(port, what); err != nil {
  85         showError(err)
  86         os.Exit(1)
  87     }
  88 }
  89 
  90 func showError(err error) {
  91     os.Stderr.WriteString("\x1b[31m")
  92     os.Stderr.WriteString(err.Error())
  93     os.Stderr.WriteString("\x1b[0m\n")
  94 }
  95 
  96 func parseArgs(args []string) (port string, path string, err error) {
  97     if len(args) == 0 || len(args) > 2 {
  98         return ``, ``, errors.New(info[1:])
  99     }
 100 
 101     if isValidPort(args[0]) {
 102         port = args[0]
 103         if len(args) == 2 {
 104             path = args[1]
 105         }
 106         return port, path, nil
 107     }
 108 
 109     if len(args) == 2 && isValidPort(args[1]) {
 110         path = args[0]
 111         port = args[1]
 112         return port, path, nil
 113     }
 114 
 115     return ``, ``, errors.New(`not given a port number to serve from`)
 116 }
 117 
 118 func isValidPort(s string) bool {
 119     if strings.HasPrefix(s, `:`) {
 120         s = s[1:]
 121     }
 122 
 123     n, err := strconv.Atoi(s)
 124     if err != nil {
 125         return false
 126     }
 127     return 1 <= n && n <= 65_535
 128 }
 129 
 130 func serveFile(port string, file string) error {
 131     http.HandleFunc(`/`, func(w http.ResponseWriter, r *http.Request) {
 132         http.ServeFile(w, r, file)
 133     })
 134     return http.ListenAndServe(port, nil)
 135 }
 136 
 137 func serveFolder(port string, path string) error {
 138     http.Handle(`/`, http.FileServer(http.Dir(path)))
 139     return http.ListenAndServe(port, nil)
 140 }