Exemplo n.º 1
0
func serve(cdir string, tld string) {
	tempDir, _ := ioutil.TempDir("", "tut")
	tempDir += string(os.PathSeparator)
	defer os.RemoveAll(tempDir)
	clog.Log("Workdir %s", tempDir)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		<-c
		os.RemoveAll(tempDir)
		clog.Fatal("Stopped")
	}()

	var idx Index
	idx = make(map[string]int)

	walker := func(src string, f os.FileInfo, err error) error {
		return setup(tempDir, src, f, idx, err)
	}

	if err := filepath.Walk(cdir, walker); err != nil {
		clog.Fatalf("Filewalk %v", err)
	}

	getindex := func(w http.ResponseWriter, r *http.Request) {
		json, err := json.Marshal(idx)
		if err != nil {
			clog.Fatalf("During Index JSON Marshal %v", err)
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(json)
	}
	http.HandleFunc("/tutorial/index.json", getindex)

	url, _ := url.Parse("http://localhost:8093")
	rp := httputil.NewSingleHostReverseProxy(url)
	http.Handle("/query", rp)

	fs := http.FileServer(http.Dir(tempDir + "/" + tld + "/"))
	http.Handle("/tutorial/", http.StripPrefix("/tutorial/", fs))

	http.Handle("/", http.RedirectHandler("/tutorial/index.html#1", 302))

	clog.Log("Running at http://localhost:8000/")
	go func() {
		for {
			filepath.Walk(cdir, walker)
			time.Sleep(2 * time.Second)
		}
	}()

	// last step
	if err := http.ListenAndServe(":8000", nil); err != nil {
		clog.Fatalf("ListenAndServe %v", err)
	}
}
Exemplo n.º 2
0
func NewHttpEndpoint(address string, staticPath string) *HttpEndpoint {
	rv := &HttpEndpoint{}

	r := mux.NewRouter()

	r.Handle("/query", rv).Methods("GET", "POST")
	r.PathPrefix("/").Handler(http.FileServer(http.Dir(staticPath)))

	go func() {
		err := http.ListenAndServe(address, r)
		if err != nil {
			clog.Fatal("ListenAndServe: ", err)
		}
	}()

	return rv
}