File: serve.go

package info (click to toggle)
golang-github-containers-buildah 1.19.6%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,020 kB
  • sloc: sh: 1,957; makefile: 199; perl: 173; awk: 12; ansic: 1
file content (40 lines) | stat: -rw-r--r-- 918 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
	"log"
	"net/http"
	"os"
	"path/filepath"
)

func sendThatFile(basepath string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		filename := filepath.Join(basepath, filepath.Clean(string([]rune{filepath.Separator})+r.URL.Path))
		f, err := os.Open(filename)
		if err != nil {
			if os.IsNotExist(err) {
				http.NotFound(w, r)
				return
			}
			http.Error(w, "whoops", http.StatusInternalServerError)
			return
		}
		finfo, err := f.Stat()
		if err != nil {
			http.Error(w, "whoops", http.StatusInternalServerError)
			return
		}
		http.ServeContent(w, r, filename, finfo.ModTime(), f)
	}
}

func main() {
	args := os.Args
	if len(args) < 3 {
		log.Fatal("requires listening port and subdirectory path")
	}
	port := args[1]
	basedir := args[2]
	http.HandleFunc("/", sendThatFile(basedir))
	log.Fatal(http.ListenAndServe(":"+port, nil))
}