Esempio n. 1
0
// Start serving the blog.
func run() {
	var (
		faviconPath  = filepath.Join(PublicDir, "favicon.ico")
		faviconCache = 2 * 24 * time.Hour
	)

	h := handlers.FaviconHandler(
		handlers.PanicHandler(
			handlers.LogHandler(
				handlers.GZIPHandler(
					http.FileServer(http.Dir(PublicDir)),
					nil),
				handlers.NewLogOptions(nil, handlers.Ldefault)),
			nil),
		faviconPath,
		faviconCache)

	// Assign the combined handler to the server.
	http.Handle("/", h)

	// Start it up.
	log.Printf("trofaf server listening on port %d", Options.Port)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", Options.Port), nil); err != nil {
		log.Fatal("FATAL ", err)
	}
}
Esempio n. 2
0
func main() {
	rand.Seed(time.Now().UTC().UnixNano())

	r := mux.NewRouter()

	r.PathPrefix("/scripts/").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))
	r.PathPrefix("/styles/").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))
	r.PathPrefix("/images/").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))
	r.PathPrefix("/fonts/").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))
	r.PathPrefix("/ico/").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))
	r.PathPrefix("/favicon.ico").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))
	r.PathPrefix("/robots.txt").Methods("GET").Handler(http.FileServer(http.Dir("./static/")))

	r.HandleFunc("/({files:.*}).zip", zipHandler).Methods("GET")
	r.HandleFunc("/({files:.*}).tar", tarHandler).Methods("GET")
	r.HandleFunc("/({files:.*}).tar.gz", tarGzHandler).Methods("GET")
	r.HandleFunc("/download/{token}/{filename}", getHandler).Methods("GET")

	r.HandleFunc("/{token}/{filename}", previewHandler).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) (match bool) {
		match = false

		// The file will show a preview page when opening the link in browser directly or
		// from external link. If the referer url path and current path are the same it will be
		// downloaded.
		if !acceptsHtml(r.Header) {
			return false
		}

		match = (r.Referer() == "")

		u, err := url.Parse(r.Referer())
		if err != nil {
			log.Fatal(err)
			return
		}

		match = match || (u.Path != r.URL.Path)
		return
	}).Methods("GET")

	r.HandleFunc("/{token}/{filename}", getHandler).Methods("GET")
	r.HandleFunc("/get/{token}/{filename}", getHandler).Methods("GET")
	r.HandleFunc("/put/{filename}", putHandler).Methods("PUT")
	r.HandleFunc("/upload/{filename}", putHandler).Methods("PUT")
	r.HandleFunc("/{filename}", putHandler).Methods("PUT")
	r.HandleFunc("/health.html", healthHandler).Methods("GET")
	r.HandleFunc("/", postHandler).Methods("POST")
	// r.HandleFunc("/{page}", viewHandler).Methods("GET")
	r.HandleFunc("/", viewHandler).Methods("GET")

	r.NotFoundHandler = http.HandlerFunc(notFoundHandler)

	port := flag.String("port", "8080", "port number, default: 8080")
	temp := flag.String("temp", config.Temp, "")
	basedir := flag.String("basedir", "", "")
	logpath := flag.String("log", "", "")
	provider := flag.String("provider", "s3", "")

	flag.Parse()

	if *logpath != "" {
		f, err := os.OpenFile(*logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalf("error opening file: %v", err)
		}

		defer f.Close()

		log.SetOutput(f)
	}

	config.Temp = *temp

	var err error

	switch *provider {
	case "local":
		if *basedir == "" {
			log.Panic("basedir not set")
		}

		storage, err = NewLocalStorage(*basedir)
	}

	if err != nil {
		log.Panic("Error while creating storage.", err)
	}

	mime.AddExtensionType(".md", "text/x-markdown")
	mime.AddExtensionType(".mkv", "video/webm")

	log.Printf("Transfer.sh server started. :\nlistening on port: %v\nusing temp folder: %s\nusing storage provider: %s", *port, config.Temp, *provider)
	log.Printf("---------------------------")

	s := &http.Server{
		Addr:    fmt.Sprintf(":%s", *port),
		Handler: handlers.PanicHandler(LoveHandler(RedirectHandler(handlers.LogHandler(r, handlers.NewLogOptions(log.Printf, "_default_")))), nil),
	}

	log.Panic(s.ListenAndServe())
	log.Printf("Server stopped.")
}
Esempio n. 3
0
// Prepare the web server and kick it off.
func main() {
	// Blank the default logger's prefixes
	log.SetFlags(0)

	// Compile the dynamic templates (native Go templates and Amber
	// templates are both registered via the for-side-effects-only imports)
	err := templates.CompileDir("./templates/")
	if err != nil {
		panic(err)
	}

	// Set the simple routes for static files
	mux := pat.New()
	mux.Get("/", handlers.StaticFileHandler("./index.html"))
	mux.Get("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public/"))))

	// Set the more complex routes for session handling and dynamic page (same
	// handler is used for both GET and POST).
	ssnOpts := handlers.NewSessionOptions(memStore, secret)
	ssnOpts.CookieTemplate.MaxAge = sessionExpiration
	hSsn := handlers.SessionHandler(
		handlers.ContextHandlerFunc(
			handlers.GhostHandlerFunc(sessionPageRenderer),
			1),
		ssnOpts)
	mux.Get("/session", hSsn)
	mux.Post("/session", hSsn)

	hAuthSsn := handlers.BasicAuthHandler(hSsn, authenticate, "")
	mux.Get("/session/auth", hAuthSsn)
	mux.Post("/session/auth", hAuthSsn)

	// Set the handler for the chained context route
	mux.Get("/context", handlers.ContextHandler(handlers.ChainHandlerFuncs(
		handlers.GhostHandlerFunc(setContext),
		handlers.GhostHandlerFunc(renderContextPage)),
		1))

	// Set the panic route, which simply panics
	mux.Get("/panic", http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			panic("explicit panic")
		}))

	// Combine the top level handlers, that wrap around the muxer.
	// Panic is the outermost, so that any panic is caught and responded to with a code 500.
	// Log is next, so that every request is logged along with the URL, status code and response time.
	// GZIP is then applied, so that content is compressed.
	// Finally, the muxer finds the specific handler that applies to the route.
	h := handlers.FaviconHandler(
		handlers.PanicHandler(
			handlers.LogHandler(
				handlers.GZIPHandler(
					mux,
					nil),
				handlers.NewLogOptions(nil, handlers.Ltiny)),
			nil),
		"./public/favicon.ico",
		48*time.Hour)

	// Assign the combined handler to the server.
	http.Handle("/", h)

	// Start it up.
	if err := http.ListenAndServe(":9000", nil); err != nil {
		panic(err)
	}
}