├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── build.sh ├── certificates.go ├── go.mod ├── go.sum └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | ### Go template 2 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 3 | *.o 4 | *.a 5 | *.so 6 | 7 | # Folders 8 | _obj 9 | _test 10 | 11 | # Architecture specific extensions/prefixes 12 | *.[568vq] 13 | [568vq].out 14 | 15 | *.cgo1.go 16 | *.cgo2.c 17 | _cgo_defun.c 18 | _cgo_gotypes.go 19 | _cgo_export.* 20 | 21 | _testmain.go 22 | 23 | *.exe 24 | *.test 25 | *.prof 26 | 27 | .idea 28 | *.iml 29 | 30 | simple_httpd 31 | simple-httpd 32 | 33 | data/* 34 | 35 | *.pem 36 | *.key 37 | *.csr 38 | *.crt 39 | *.srl 40 | 41 | bin/* 42 | 43 | .DS_Store 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - "1.15" 5 | - "tip" 6 | 7 | # Skip the install step. Don't `go get` dependencies. Only build with the 8 | # code in vendor/ 9 | install: true 10 | 11 | matrix: 12 | # It's ok if our code fails on unstable development versions of Go. 13 | allow_failures: 14 | - go: master 15 | # Don't wait for tip tests to finish. Mark the test run green if the 16 | # tests pass on the stable versions of Go. 17 | fast_finish: true 18 | 19 | # Don't email me the results of the test runs. 20 | notifications: 21 | email: false 22 | 23 | # Anything in before_script that returns a nonzero exit code will 24 | # flunk the build and immediately stop. It's sorta like having 25 | # set -e enabled in bash. 26 | before_script: 27 | - GO_FILES=$(find . -iname '*.go' -type f | grep -v /vendor/) # All the .go files, excluding vendor/ 28 | - go get golang.org/x/lint/golint 29 | 30 | # script always run to completion (set +e). All of these code checks are must haves 31 | # in a modern Go project. 32 | script: 33 | - test -z $(gofmt -s -l $GO_FILES) # Fail if a .go file hasn't been formatted with gofmt 34 | - go test -race -v ./... # Run all the tests with the race detector enabled 35 | - go vet ./... # go vet is the official Go static analyzer 36 | - golint $(go list ./...) # one last linter 37 | 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GO = go 2 | 3 | BINDIR := bin 4 | BINARY := simple-httpd 5 | PREFIX := /usr/local 6 | 7 | VERSION = v0.5.0 8 | GIT_SHA = $(shell git rev-parse HEAD) 9 | LDFLAGS = -ldflags "-X main.gitSHA=$(GIT_SHA) -X main.version=$(VERSION) -X main.name=$(BINARY)" 10 | 11 | OS := $(shell uname) 12 | 13 | $(BINDIR)/$(BINARY): clean 14 | $(GO) build $(LDFLAGS) -o $@ 15 | 16 | .PHONY: test 17 | test: 18 | $(GO) test -v . 19 | 20 | .PHONY: clean 21 | clean: 22 | $(GO) clean 23 | rm -f $(BINARY) 24 | rm -f $(BINDIR)/* 25 | 26 | .PHONY: install 27 | install: clean 28 | ifeq ($(OS),Darwin) 29 | ./build.sh darwin $(BINARY) $(VERSION) $(GIT_SHA) 30 | cp -f $(BINDIR)/$(BINARY)-darwin $(PREFIX)/$(BINDIR)/$(BINARY) 31 | endif 32 | ifeq ($(OS),Linux) 33 | ./build.sh linux $(BINARY) $(VERSION) $(GIT_SHA) 34 | cp -f $(BINDIR)/$(BINARY)-linux $(PREFIX)/$(BINDIR)/$(BINARY) 35 | endif 36 | ifeq ($(OS),FreeBSD) 37 | ./build.sh freebsd $(BINARY) $(VERSION) $(GIT_SHA) 38 | cp -f $(BINDIR)/$(BINARY)-freebsd $(PREFIX)/$(BINDIR)/$(BINARY) 39 | endif 40 | uninstall: 41 | rm -f $(PREFIX)/$(BINDIR)/$(BINARY)* 42 | 43 | .PHONY: release 44 | release: clean 45 | ./build.sh release $(BINARY) $(VERSION) $(GIT_SHA) 46 | 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simple-httpd 2 | 3 | [![Build Status](https://travis-ci.org/briandowns/simple-httpd.svg?branch=master)](https://travis-ci.org/briandowns/simple-httpd) 4 | 5 | simple-httpd is aimed to be a simple replacement for using `python -m SimpleHTTPServer` to serve local files. Like [SimpleHTTPServer](https://docs.python.org/2/library/simplehttpserver.html), simple-httpd supports HTTP GET and HEAD requests and adheres to the [HTTP/1.1 RFC 2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) guidelines. 6 | 7 | The HTML output is a mix of the Python module layout and of an Apache directory listing layout. 8 | 9 | If you're looking for a full featured or even just more capable web server, take a look at [Caddy](https://caddyserver.com/). 10 | 11 | ## Features 12 | 13 | * HTTP2 with [Let's Encrypt](https://letsencrypt.org/) integration for automatic TLS, if enabled. 14 | * Automatic self signed certificate generation and use, if enabled. 15 | * Multiple language support: English, Italian, Spanish, Irish. ISO 639-1 are given on the CLI. 16 | 17 | Certificates are cached in `${HOME}/.autocert` for reuse. 18 | 19 | ## Installation 20 | 21 | ``` 22 | go get github.com/briandowns/simple-httpd 23 | ``` 24 | or 25 | ``` 26 | make install 27 | ``` 28 | or, on BSD 29 | ``` 30 | gmake install 31 | ``` 32 | 33 | ### Examples 34 | 35 | HTTP/1.1 on default port (8000) 36 | 37 | ``` 38 | simple-httpd 39 | ``` 40 | 41 | HTTP/1.1 on the given port 42 | 43 | ``` 44 | simple-httpd -p 8181 45 | ``` 46 | 47 | HTTP/2 with Let's Encrypt on the default port 48 | 49 | ``` 50 | simple-httpd -l some.valid.domain 51 | ``` 52 | 53 | The port assignment is for the HTTP server. The TLS port will be 8081 and both will respond to requests. 54 | 55 | ``` 56 | simple-httpd -p 8080 -t some.valid.domain 57 | ``` 58 | 59 | Generate a self signed certificate and run the server 60 | 61 | ``` 62 | simple-httpd -g 63 | ``` 64 | 65 | Run server in Spanish 66 | 67 | ``` 68 | simple-httpd -l es 69 | 70 | ## Contributions 71 | 72 | * File Issue with details of the problem, feature request, etc. 73 | * Submit a pull request and include details of what problem or feature the code is solving or implementing. 74 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | OSs="darwin linux freebsd windows" 4 | ARCHs="arm64 amd64" 5 | 6 | if [ -z $1 ]; then 7 | echo "error: requires argument of [release|freebsd|darwin|linux|windows]" 8 | exit 1 9 | fi 10 | OS=$1 11 | 12 | if [ -z $2 ]; then 13 | echo "error: requires argument of " 14 | exit 1 15 | fi 16 | BINARY=$2 17 | 18 | if [ -z $3 ]; then 19 | echo "error: requires argument of " 20 | exit 1 21 | fi 22 | VERSION=$3 23 | 24 | if [ -z $4 ]; then 25 | echo "error: requires argument of " 26 | exit 1 27 | fi 28 | 29 | GIT_SHA=$4 30 | 31 | if [ ${OS} == "release" ]; then 32 | echo "Generating ${BINARY} release binaries..." 33 | for os in ${OSs}; do 34 | for arch in ${ARCHs}; do 35 | if [ ${arch} = "arm64" ] && [ ${os} = "windows" ]; then 36 | continue 37 | fi 38 | if [ ${arch} = "arm64" ] && [ ${os} = "darwin" ]; then 39 | continue 40 | fi 41 | GOOS=${os} GOARCH=${arch} go build -v -ldflags "-X main.gitSHA=${GIT_SHA} -X main.version=${VERSION} -X main.name=${BINARY}" -o bin/${BINARY}-${os}-${arch} 42 | done 43 | done 44 | fi 45 | 46 | exit 0 47 | -------------------------------------------------------------------------------- /certificates.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // most of the certificate stuff shamelessly lifted from the 4 | // example found here https://golang.org/src/crypto/tls/generate_cert.go 5 | 6 | import ( 7 | "crypto/ecdsa" 8 | "crypto/elliptic" 9 | "crypto/rand" 10 | "crypto/rsa" 11 | "crypto/x509" 12 | "crypto/x509/pkix" 13 | "encoding/pem" 14 | "fmt" 15 | "math/big" 16 | "net" 17 | "os" 18 | "time" 19 | ) 20 | 21 | // namesAndAddresses generates a slice of hostnames and addresses 22 | // to generate certificates for. 23 | func namesAndAddresses() ([]string, error) { 24 | var r []string 25 | 26 | ifaces, err := net.Interfaces() 27 | if err != nil { 28 | return nil, err 29 | } 30 | 31 | for _, i := range ifaces { 32 | addrs, err := i.Addrs() 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | for _, addr := range addrs { 38 | switch v := addr.(type) { 39 | case *net.IPNet: 40 | r = append(r, v.IP.String()) 41 | } 42 | } 43 | } 44 | 45 | h, err := os.Hostname() 46 | if err != nil { 47 | return nil, err 48 | } 49 | r = append(r, h) 50 | 51 | return r, nil 52 | } 53 | 54 | var ecdsaCurve = "" 55 | 56 | // publicKey 57 | func publicKey(priv interface{}) interface{} { 58 | switch k := priv.(type) { 59 | case *rsa.PrivateKey: 60 | return &k.PublicKey 61 | case *ecdsa.PrivateKey: 62 | return &k.PublicKey 63 | default: 64 | return nil 65 | } 66 | } 67 | 68 | // pemBlockForKey 69 | func pemBlockForKey(priv interface{}) *pem.Block { 70 | switch k := priv.(type) { 71 | case *rsa.PrivateKey: 72 | return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} 73 | case *ecdsa.PrivateKey: 74 | b, err := x509.MarshalECPrivateKey(k) 75 | if err != nil { 76 | fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err) 77 | os.Exit(2) 78 | } 79 | return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} 80 | default: 81 | return nil 82 | } 83 | } 84 | 85 | // generateCertificates will generate a certificate and key and save them to 86 | // the given paths. 87 | func generateCertificates(certPath, keyPath string) error { 88 | var priv interface{} 89 | var err error 90 | switch ecdsaCurve { 91 | case "": 92 | priv, err = rsa.GenerateKey(rand.Reader, 4096) 93 | case "P224": 94 | priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) 95 | case "P256": 96 | priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 97 | case "P384": 98 | priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) 99 | case "P521": 100 | priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) 101 | default: 102 | return fmt.Errorf("unrecognized elliptic curve: %q", ecdsaCurve) 103 | } 104 | if err != nil { 105 | return err 106 | } 107 | 108 | start := time.Now() 109 | expire := start.Add(365 * 24 * time.Hour) 110 | 111 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) 112 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) 113 | if err != nil { 114 | return err 115 | } 116 | 117 | template := x509.Certificate{ 118 | SerialNumber: serialNumber, 119 | Subject: pkix.Name{ 120 | Organization: []string{"Acme Co"}, 121 | }, 122 | NotBefore: start, 123 | NotAfter: expire, 124 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 125 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 126 | BasicConstraintsValid: true, 127 | } 128 | 129 | hosts, err := namesAndAddresses() 130 | if err != nil { 131 | return err 132 | } 133 | 134 | for _, h := range hosts { 135 | if ip := net.ParseIP(h); ip != nil { 136 | template.IPAddresses = append(template.IPAddresses, ip) 137 | } else { 138 | template.DNSNames = append(template.DNSNames, h) 139 | } 140 | } 141 | 142 | template.IsCA = true 143 | template.KeyUsage |= x509.KeyUsageCertSign 144 | 145 | derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) 146 | if err != nil { 147 | return err 148 | } 149 | 150 | certOut, err := os.Create(certPath) 151 | if err != nil { 152 | return err 153 | } 154 | 155 | if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { 156 | return err 157 | } 158 | 159 | if err := certOut.Close(); err != nil { 160 | return err 161 | } 162 | 163 | keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) 164 | if err != nil { 165 | return err 166 | } 167 | 168 | if err := pem.Encode(keyOut, pemBlockForKey(priv)); err != nil { 169 | return err 170 | } 171 | 172 | return keyOut.Close() 173 | } 174 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/briandowns/simple-httpd 2 | 3 | go 1.15 4 | 5 | require ( 6 | go.uber.org/zap v1.16.0 7 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= 5 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 6 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 7 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 8 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 9 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 10 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 11 | github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= 12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 13 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 14 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 15 | go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= 16 | go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= 17 | go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= 18 | go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= 19 | go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= 20 | go.uber.org/zap v1.16.0 h1:uFRZXykJGK9lLY4HtgSw44DnIcAM+kRBP7x5m+NpAOM= 21 | go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= 22 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 23 | golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 24 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= 25 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= 26 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 27 | golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= 28 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 29 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= 30 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 31 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= 32 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 33 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 34 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 35 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 36 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 37 | golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= 38 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 39 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 40 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 41 | golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= 42 | golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 43 | golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 44 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 45 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 46 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 47 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= 48 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 49 | honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= 50 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Brian J. Downs 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "crypto/tls" 19 | "errors" 20 | "flag" 21 | "fmt" 22 | "html/template" 23 | "io" 24 | "mime" 25 | "net/http" 26 | "net/url" 27 | "os" 28 | "os/user" 29 | "path" 30 | "path/filepath" 31 | "runtime" 32 | "strconv" 33 | "strings" 34 | "time" 35 | 36 | "go.uber.org/zap" 37 | "golang.org/x/crypto/acme/autocert" 38 | ) 39 | 40 | var ( 41 | name string 42 | version string 43 | // gitSHA is populated at build time from 44 | // `-ldflags "-X main.gitSHA=$(shell git rev-parse HEAD)"` 45 | gitSHA string 46 | ) 47 | 48 | var indexHTMLFiles = []string{ 49 | "index.html", 50 | "index.htm", 51 | } 52 | 53 | const ( 54 | cert = "cert.pem" 55 | key = "key.pem" 56 | certDir = ".autocert" 57 | 58 | pathSeperator = "/" 59 | 60 | defaultPort = 8000 61 | ) 62 | 63 | var directoryText string 64 | 65 | // Data holds the data passed to the template engine. 66 | type Data struct { 67 | Name string 68 | LastModified string 69 | URI string 70 | Size int64 71 | } 72 | 73 | // httpServer holds the relavent info/state. 74 | type httpServer struct { 75 | Directory string 76 | Port int 77 | TLSPort int 78 | HTTPS bool 79 | template *template.Template 80 | } 81 | 82 | // setHeaders sets the base headers for all requests. 83 | func setHeaders(w http.ResponseWriter) { 84 | w.Header().Set("Server", name+pathSeperator+version) 85 | w.Header().Add("Date", time.Now().Format(time.RFC822)) 86 | } 87 | 88 | // isIndexFile determines if the given file is one 89 | // of the accepted index files. 90 | func isIndexFile(file string) bool { 91 | for _, s := range indexHTMLFiles { 92 | if s == file { 93 | return true 94 | } 95 | } 96 | return false 97 | } 98 | 99 | // ServeHTTP handles inbound requests. 100 | func (h *httpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { 101 | if h.HTTPS && req.TLS == nil { 102 | url := "https://" + strings.Split(req.Host, ":")[0] 103 | if h.TLSPort != 443 { 104 | url = url + ":" + strconv.FormatInt(int64(h.TLSPort), 10) 105 | } 106 | url += req.URL.String() 107 | http.Redirect(w, req, url, http.StatusFound) 108 | return 109 | } 110 | defer func() { 111 | if err := recover(); err != nil { 112 | http.Error(w, fmt.Sprintln(err), http.StatusInternalServerError) 113 | log.Error("msg", zap.Error(fmt.Errorf("recovering from error: %s", err))) 114 | } 115 | }() 116 | 117 | parsedURL, err := url.Parse(req.RequestURI) 118 | if err != nil { 119 | log.Error("msg", 120 | zap.String("method", req.Method), 121 | zap.String("remote_addr", req.RemoteAddr), 122 | zap.String("path", req.RequestURI), 123 | zap.String("user_agent", req.UserAgent()), 124 | zap.Int("status", http.StatusInternalServerError), 125 | zap.Error(err)) 126 | http.Error(w, err.Error(), http.StatusInternalServerError) 127 | return 128 | } 129 | 130 | // check if we have a file with spaces in the name and 131 | // replace the %20 with an actual space. 132 | escapedPath := parsedURL.EscapedPath() 133 | if strings.Contains(escapedPath, "%20") { 134 | escapedPath = strings.ReplaceAll(escapedPath, "%20", " ") 135 | } 136 | 137 | fullpath := filepath.Join(h.Directory, escapedPath[1:]) 138 | 139 | file, err := os.Open(fullpath) 140 | if err != nil { 141 | log.Error("msg", 142 | zap.String("method", req.Method), 143 | zap.String("remote_addr", req.RemoteAddr), 144 | zap.String("path", req.RequestURI), 145 | zap.String("user_agent", req.UserAgent()), 146 | zap.Int("status", http.StatusInternalServerError), 147 | zap.Error(err)) 148 | http.NotFound(w, req) 149 | return 150 | } 151 | defer file.Close() 152 | 153 | stat, err := file.Stat() 154 | if err != nil { 155 | log.Error("msg", 156 | zap.String("method", req.Method), 157 | zap.String("remote_addr", req.RemoteAddr), 158 | zap.String("path", req.RequestURI), 159 | zap.String("user_agent", req.UserAgent()), 160 | zap.Int("status", http.StatusInternalServerError), 161 | zap.Error(err)) 162 | w.WriteHeader(http.StatusInternalServerError) 163 | return 164 | } 165 | 166 | setHeaders(w) 167 | 168 | if stat.IsDir() { 169 | if escapedPath[len(escapedPath)-1] != '/' { 170 | // Redirect all directory requests to ensure they end with a slash 171 | http.Redirect(w, req, escapedPath+"/", http.StatusFound) 172 | log.Error("msg", 173 | zap.String("method", req.Method), 174 | zap.String("remote_addr", req.RemoteAddr), 175 | zap.String("path", req.RequestURI), 176 | zap.String("user_agent", req.UserAgent()), 177 | zap.Int("status", http.StatusFound)) 178 | return 179 | } 180 | 181 | contents, err := file.Readdir(-1) 182 | if err != nil { 183 | log.Error("msg", 184 | zap.String("method", req.Method), 185 | zap.String("remote_addr", req.RemoteAddr), 186 | zap.String("path", req.RequestURI), 187 | zap.String("user_agent", req.UserAgent()), 188 | zap.Int("status", http.StatusInternalServerError), 189 | zap.Error(err)) 190 | w.WriteHeader(http.StatusInternalServerError) 191 | return 192 | } 193 | 194 | files := make([]Data, 0, len(contents)) 195 | for _, entry := range contents { 196 | if isIndexFile(entry.Name()) { 197 | w.Header().Set("Content-type", "text/html; charset=UTF-8") 198 | w.Header().Set("Content-Length", fmt.Sprintf("%v", entry.Size())) 199 | 200 | hf, err := os.Open(filepath.Join(fullpath, entry.Name())) 201 | if err != nil { 202 | log.Error("msg", zap.Error(err)) 203 | return 204 | } 205 | if _, err := io.Copy(w, hf); err != nil { 206 | log.Error("msg", zap.Error(err)) 207 | return 208 | } 209 | 210 | log.Info("request", 211 | zap.String("method", req.Method), 212 | zap.String("remote_addr", req.RemoteAddr), 213 | zap.String("path", req.RequestURI), 214 | zap.String("user_agent", req.UserAgent()), 215 | zap.Int("status", http.StatusOK)) 216 | return 217 | } 218 | file := Data{ 219 | Name: entry.Name(), 220 | LastModified: entry.ModTime().Format(time.RFC1123), 221 | URI: path.Join(escapedPath, entry.Name()), 222 | Size: entry.Size(), 223 | } 224 | if entry.IsDir() { 225 | file.Name = entry.Name() + pathSeperator 226 | } 227 | files = append(files, file) 228 | } 229 | 230 | w.Header().Set("Content-type", "text/html; charset=UTF-8") 231 | 232 | if err := h.template.Execute(w, map[string]interface{}{ 233 | "files": files, 234 | "gitSha": gitSHA, 235 | "version": version, 236 | "port": h.Port, 237 | "relativePath": fullpath, 238 | "goVersion": runtime.Version(), 239 | "lang": lang, 240 | "name": name, 241 | "directoryText": directoryText, 242 | "parentDirectory": path.Clean(escapedPath + "/.."), 243 | }); err != nil { 244 | log.Error("msg", zap.Error(err)) 245 | return 246 | } 247 | 248 | log.Info("request", 249 | zap.String("method", req.Method), 250 | zap.String("remote_addr", req.RemoteAddr), 251 | zap.String("path", req.RequestURI), 252 | zap.String("user_agent", req.UserAgent()), 253 | zap.Int("status", http.StatusOK)) 254 | return 255 | } 256 | 257 | if mimetype := mime.TypeByExtension(path.Ext(file.Name())); mimetype != "" { 258 | w.Header().Set("Content-type", mimetype) 259 | } else { 260 | w.Header().Set("Content-type", "application/octet-stream") 261 | } 262 | 263 | if _, err := io.Copy(w, file); err != nil { 264 | log.Error("msg", zap.Error(err)) 265 | 266 | return 267 | } 268 | 269 | log.Info("request", 270 | zap.String("method", req.Method), 271 | zap.String("remote_addr", req.RemoteAddr), 272 | zap.String("path", req.RequestURI), 273 | zap.String("user_agent", req.UserAgent()), 274 | zap.Int("status", http.StatusOK)) 275 | } 276 | 277 | const usage = `version: %s 278 | 279 | Usage: %[2]s [-p port] [-e domain] 280 | 281 | Options: 282 | -h help 283 | -v show version and exit 284 | -g enable TLS/HTTPS generate and use a self signed certificate 285 | -p port bind HTTP port (default: 8000) 286 | -e domain enable TLS/HTTPS with Let's Encrypt for the given domain name 287 | -c path enable TLS/HTTPS with a predefined HTTPS certificate 288 | -t port bind HTTPS port (default: 443, 4433 for -g) 289 | -l lang language code (ISO 639-1) to for UI. (default: en) 290 | 291 | Examples: 292 | %[2]s start server. http://localhost:8000 293 | %[2]s -p 80 use HTTP port 80. http://localhost 294 | %[2]s -g enable HTTPS generated certificate. https://localhost:4433 295 | %[2]s -p 80 -e example.com enable HTTPS with Let's Encrypt. https://example.com 296 | ` 297 | 298 | const warmUpDelay = time.Millisecond * 10 299 | 300 | var ( 301 | port int 302 | le string 303 | gs bool 304 | tlsPort int 305 | tlsCert string 306 | vers bool 307 | lang string 308 | ) 309 | 310 | var log *zap.Logger 311 | 312 | // setDirectoryText sets the text for the directory listing. 313 | func setDirectoryText(alng string) error { 314 | switch lang { 315 | case "it": 316 | directoryText = "L'elenco di directory per" 317 | case "es": 318 | directoryText = "Listado de directorio para" 319 | case "ga": 320 | directoryText = "Comhadlann liostú do" 321 | case "en", "": 322 | directoryText = "Directory listing for" 323 | default: 324 | return fmt.Errorf("error: invalid language: %s", lang) 325 | } 326 | return nil 327 | } 328 | 329 | func main() { 330 | var err error 331 | log, err = zap.NewProduction() 332 | if err != nil { 333 | fmt.Println(err) 334 | os.Exit(1) 335 | } 336 | defer log.Sync() 337 | 338 | pwd, err := os.Getwd() 339 | if err != nil { 340 | fmt.Println(err) 341 | os.Exit(1) 342 | } 343 | 344 | flag.Usage = func() { 345 | w := os.Stderr 346 | for _, arg := range os.Args { 347 | if arg == "-h" { 348 | w = os.Stdout 349 | break 350 | } 351 | } 352 | fmt.Fprintf(w, usage, version, name) 353 | } 354 | 355 | flag.BoolVar(&vers, "v", false, "") 356 | flag.IntVar(&port, "p", defaultPort, "") 357 | flag.StringVar(&le, "e", "", "") 358 | flag.StringVar(&tlsCert, "c", "", "") 359 | flag.BoolVar(&gs, "g", false, "") 360 | flag.IntVar(&tlsPort, "t", -1, "") 361 | flag.StringVar(&lang, "l", "en", "") 362 | flag.Parse() 363 | 364 | if vers { 365 | fmt.Fprintf(os.Stdout, "version: %s - git sha: %s\n", version, gitSHA) 366 | return 367 | } 368 | 369 | if tlsPort == -1 { 370 | if gs { 371 | tlsPort = 4433 372 | } else { 373 | tlsPort = 443 374 | } 375 | } 376 | 377 | if err := setDirectoryText(lang); err != nil { 378 | fmt.Println(err) 379 | os.Exit(1) 380 | } 381 | 382 | h := &httpServer{ 383 | Port: port, 384 | TLSPort: tlsPort, 385 | Directory: pwd, 386 | template: template.Must(template.New("listing").Parse(htmlTemplate)), 387 | } 388 | 389 | if le != "" || tlsCert != "" || gs { 390 | h.HTTPS = true 391 | 392 | var tlsServer *http.Server 393 | var certPath string 394 | var keyPath string 395 | 396 | u, err := user.Current() 397 | if err != nil { 398 | fmt.Println(err) 399 | os.Exit(1) 400 | } 401 | 402 | switch { 403 | case tlsCert != "": 404 | if gs { 405 | fmt.Println(errors.New("cannot specify both -tls-cert and -g")) 406 | os.Exit(1) 407 | } 408 | certPath, keyPath = tlsCert, tlsCert // assume a single PEM format 409 | case gs: 410 | hd := u.HomeDir 411 | certPath = filepath.Join(hd, certDir, cert) 412 | keyPath = filepath.Join(hd, certDir, key) 413 | if err := generateCertificates(certPath, keyPath); err != nil { 414 | fmt.Println(err) 415 | os.Exit(1) 416 | } 417 | default: 418 | if tlsPort != 443 { 419 | fmt.Printf("invalid -tls-port %d. It must be 443 when LetsEncrypt is specified\n", tlsPort) 420 | os.Exit(1) 421 | } 422 | 423 | cacheDir := filepath.Join(u.HomeDir, certDir) 424 | 425 | if err := os.MkdirAll(cacheDir, 0700); err != nil { 426 | fmt.Printf("could not create cache directory: %s\n", cacheDir) 427 | os.Exit(1) 428 | } 429 | 430 | certManager := autocert.Manager{ 431 | Cache: autocert.DirCache(cacheDir), 432 | Prompt: autocert.AcceptTOS, 433 | HostPolicy: autocert.HostWhitelist(le), 434 | } 435 | 436 | tlsServer = &http.Server{ 437 | Addr: fmt.Sprintf(":%d", tlsPort), 438 | TLSConfig: &tls.Config{ 439 | GetCertificate: certManager.GetCertificate, 440 | }, 441 | Handler: h, 442 | } 443 | } 444 | 445 | go func() { 446 | var err error 447 | if tlsServer == nil { 448 | err = http.ListenAndServeTLS(fmt.Sprintf("0.0.0.0:%d", tlsPort), certPath, keyPath, h) 449 | } else { 450 | err = tlsServer.ListenAndServeTLS("", "") 451 | } 452 | if err != nil { 453 | log.Fatal("msg", zap.Error(err)) 454 | } 455 | }() 456 | 457 | time.Sleep(warmUpDelay) // give a little warmup time to the TLS 458 | log.Info("msg", zap.String("Serving HTTP on", "0.0.0.0"), zap.Int("port", h.Port), zap.Int("https", tlsPort)) 459 | } else { 460 | go func() { 461 | time.Sleep(warmUpDelay) // give a little warmup time to the HTTP 462 | log.Info("msg", zap.String("Serving HTTP on", "0.0.0.0"), zap.Int("port", h.Port)) 463 | }() 464 | } 465 | 466 | log.Fatal("msg", zap.Error(http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), h))) 467 | } 468 | 469 | const htmlTemplate = ` 470 | 471 | 472 | 473 | 474 | {{.name}} 475 | 480 | 481 | 482 |

{{.directoryText}} {{.relativePath}}

483 |
484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | {{range .files}} 496 | 497 | 498 | 499 | 500 | 501 | {{end}} 502 |
NameLast ModifiedSize
{{.parentDirectory}}
{{.Name}}{{.LastModified}}{{.Size}}
503 | 504 |
505 |
506 |

{{.name}} {{.version}} - {{.gitSha}} / {{.goVersion}}

507 |
508 | ` 509 | --------------------------------------------------------------------------------