main.go 1.98 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
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
package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
	"text/template"
)

const templateFile = "../dir-index.html"

// Copied from go-ipfs/core/corehttp/gateway_indexPage.go
type listingTemplateData struct {
	Listing  []directoryItem
	Path     string
	BackLink string
	Hash     string
}

type directoryItem struct {
	Size string
	Name string
	Path string
}

var testData = listingTemplateData{
	Listing: []directoryItem{{
		Size: "25 MiB",
		Name: "short-film.mov",
		Path: "short-film.mov",
	}, {
		Size: "1 KiB",
Jessica Schilling's avatar
Jessica Schilling committed
34
		Name: "this-piece-of-papers-got-47-words-37-sentences-58-words-we-wanna-know.txt",
Jessica Schilling's avatar
Jessica Schilling committed
35
		Path: "this-piece-of-papers-got-47-words-37-sentences-58-words-we-wanna-know.txt",
Steven Allen's avatar
Steven Allen committed
36
	}},
37
	Path:     "/ipfs/QmFooBarQXB2mzChmMeKY47C43LxUdg1NDJ5MWcKMKxDu7RgQm",
Steven Allen's avatar
Steven Allen committed
38
	BackLink: "/..",
Jessica Schilling's avatar
Jessica Schilling committed
39
	Hash:     "QmFooBarQXB2mzChmMeKY47C43LxUdg1NDJ5MWcKMKxDu7RgQm",
Steven Allen's avatar
Steven Allen committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" {
			http.Error(w, "Ha-ha, tricked you! There are no files here!", http.StatusNotFound)
			return
		}
		listingTemplate, err := template.New("dir-index.html").Funcs(template.FuncMap{
			"iconFromExt": func(name string) string {
				return "ipfs-_blank" // place-holder
			},
			"urlEscape": func(rawUrl string) string {
				pathUrl := url.URL{Path: rawUrl}
				return pathUrl.String()
			},
		}).ParseFiles(templateFile)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to parse template file: %s", err), http.StatusInternalServerError)
			return
		}
		err = listingTemplate.Execute(w, &testData)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to execute template: %s", err), http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
	if _, err := os.Stat(templateFile); err != nil {
		wd, _ := os.Getwd()
		fmt.Printf("could not open template file %q, relative to %q: %s\n", templateFile, wd, err)
		os.Exit(1)
	}
	fmt.Printf("listening on localhost:3000\n")
	http.ListenAndServe("localhost:3000", mux)
}