Exemple #1
0
func init() {
	// Silence log output
	log.SetOutput(nil)

	// setup mime
	mime.AddExtensionType(".foo", "foo/bar")
	mime.AddExtensionType(".json", "application/json")
	mime.AddExtensionType(".txt", "text/plain")
	mime.AddExtensionType(".png", "image/png")
	mime.AddExtensionType(".html", "text/html")

	go func() {

		// falcore setup
		pipeline := falcore.NewPipeline()
		pipeline.Upstream.PushBack(&FileFilter{
			PathPrefix:     "/",
			BasePath:       "../test/",
			DirectoryIndex: "index.html",
		})
		srv = falcore.NewServer(0, pipeline)
		if err := srv.ListenAndServe(); err != nil {
			panic(fmt.Sprintf("Could not start falcore: %v", err))
		}
	}()
}
Exemple #2
0
func init() {
	if err := mime.AddExtensionType(".rmvb", "application/vnd.rn-realmedia-vbr"); err != nil {
		panic(err)
	}
	if err := mime.AddExtensionType(".ogv", "video/ogg"); err != nil {
		panic(err)
	}
}
Exemple #3
0
func main() {
	//	beego.AutoRender = false
	beego.ViewsPath = "tpl" //模板存储目录
	beego.SessionOn = true  //SESSION开启

	mime.AddExtensionType(".css", "text/css")              //CSS 输出页头Content-Type
	mime.AddExtensionType(".js", "application/javascript") //JS 输出页头Content-Type
	beego.SetStaticPath("/static", "static")               //注册静态文件目录
	beego.Errorhandler("404", page404)
	beego.Run()
}
Exemple #4
0
func init() {
	// Add some types we want to be able to handle which can be missing by default
	mime.AddExtensionType(".json", "application/json")
	mime.AddExtensionType(".yml", "application/yaml")
	mime.AddExtensionType(".yaml", "application/yaml")

	sourceReaders = make(map[string]func(*Source) ([]byte, error))

	// Register our source-reader functions
	addSourceReader("http", readHTTP)
	addSourceReader("https", readHTTP)
	addSourceReader("file", readFile)
}
Exemple #5
0
Fichier : web.go Projet : Remo/web
func (s *Server) initServer() {
	if s.Config == nil {
		s.Config = &ServerConfig{}
	}

	if s.Logger == nil {
		s.Logger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
	}
	// Set two commonly used mimetypes that are often not set by default
	// Handy for robots.txt and favicon.ico
	mime.AddExtensionType(".txt", "text/plain; charset=utf-8")
	mime.AddExtensionType(".ico", "image/x-icon")
}
Exemple #6
0
func MimeType(args []string) {
	filename := args[0]
	ext := filepath.Ext(filename)
	mime.AddExtensionType(".gz", "application/gzip")
	mime.AddExtensionType(".tgz", "application/gzip")
	mime.AddExtensionType(".tar", "application/tar")
	mime.AddExtensionType(".zip", "application/zip")
	mimetype := mime.TypeByExtension(ext)
	if mimetype != "" {
		fmt.Println(mimetype)
	} else {
		fmt.Println("application/octet-stream")
	}
}
Exemple #7
0
// Setup all routers, handlers and start a HTTP server (blocking call)
func (api *RESTfulAPI) start(catalogStorage catalog.CatalogStorage) {
	api.mountCatalog(catalogStorage)
	api.mountResources()

	api.router.Methods("GET", "POST").Path("/dashboard").HandlerFunc(api.dashboardHandler(*confPath))
	api.router.Methods("GET").Path(api.restConfig.Location).HandlerFunc(api.indexHandler())

	err := mime.AddExtensionType(".jsonld", "application/ld+json")
	if err != nil {
		logger.Println("RESTfulAPI.start() ERROR:", err.Error())
	}

	// Configure the middleware
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		&negroni.Static{
			Dir:       http.Dir(api.config.StaticDir),
			Prefix:    StaticLocation,
			IndexFile: "index.html",
		},
	)
	// Mount router
	n.UseHandler(api.router)

	// Start the listener
	addr := fmt.Sprintf("%v:%v", api.config.Http.BindAddr, api.config.Http.BindPort)
	logger.Printf("RESTfulAPI.start() Starting server at http://%v%v", addr, api.restConfig.Location)
	n.Run(addr)
}
Exemple #8
0
func init() {
	// add missing extensions
	for k, v := range mimeRdfExt {
		mime.AddExtensionType(k, v)
	}

	for _, syntax := range crdf.ParserSyntax {
		switch syntax.MimeType {
		case "", "text/html":
			continue
		}
		mimeParser[syntax.MimeType] = syntax.Name
	}
	mimeParser["text/n3"] = mimeParser["text/turtle"]

	for name, syntax := range crdf.SerializerSyntax {
		switch name {
		case "json-triples":
			// only activate: json
			continue
		case "rdfxml-xmp", "rdfxml":
			// only activate: rdfxml-abbrev
			continue
		}
		mimeSerializer[syntax.MimeType] = syntax.Name
	}

	for mime := range mimeSerializer {
		switch mime {
		case "application/xhtml+xml":
			continue
		}
		serializerMimes = append(serializerMimes, mime)
	}
}
Exemple #9
0
func Serve(httpAddress *string, db core.Database, s *search.Searcher, devAssets bool, updater *torrent.StatsUpdater) {

	// Add SVG to mime directory
	mime.AddExtensionType(".svg", "image/svg+xml")

	r := mux.NewRouter()

	apirouter := ApiRouter(db, s, updater)

	r.PathPrefix("/api/").Handler(apirouter)
	if devAssets {
		log.Println("Debug mode is on. Serving development assets from angular/app.")
		r.PathPrefix("/styles/").Handler(http.FileServer(http.Dir("frontend/angular/.tmp/")))
		r.PathPrefix("/bower_components/").Handler(http.FileServer(http.Dir("frontend/angular/")))
		r.PathPrefix("/").Handler(NotFoundHook{
			http.FileServer(http.Dir("frontend/angular/app/")),
			"frontend/angular/app/index.html"})
	} else {
		r.PathPrefix("/").Handler(NotFoundHook{
			http.FileServer(http.Dir("frontend/angular/dist/")),
			"frontend/angular/dist/index.html"})
	}
	http.Handle("/", r)
	log.Println("Web server listening on", *httpAddress)
	err := http.ListenAndServe(*httpAddress, nil)
	if err != nil {
		log.Println(err)
	}
}
Exemple #10
0
func init() {
	playScript(basePath, "HTTPTransport")
	present.PlayEnabled = true

	// App Engine has no /etc/mime.types
	mime.AddExtensionType(".svg", "image/svg+xml")
}
Exemple #11
0
func init() {
	initHugoBuilderFlags(serverCmd)

	serverCmd.Flags().IntVarP(&serverPort, "port", "p", 1313, "port on which the server will listen")
	serverCmd.Flags().StringVarP(&serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind")
	serverCmd.Flags().BoolVarP(&serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed")
	serverCmd.Flags().BoolVarP(&serverAppend, "appendPort", "", true, "append port to baseurl")
	serverCmd.Flags().BoolVar(&disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild")
	serverCmd.Flags().BoolVar(&renderToDisk, "renderToDisk", false, "render to Destination path (default is render to memory & serve from there)")
	serverCmd.Flags().String("memstats", "", "log memory usage to this file")
	serverCmd.Flags().Int("meminterval", 100, "interval to poll memory usage (requires --memstats)")
	serverCmd.RunE = server

	mime.AddExtensionType(".json", "application/json; charset=utf-8")
	mime.AddExtensionType(".css", "text/css; charset=utf-8")

}
Exemple #12
0
func main() {
	mime.AddExtensionType(".ico", "image/x-icon")
	mime.AddExtensionType(".svg", "image/svg+xml")

	fileHandler := http.FileServer(http.Dir("/content"))
	http.Handle("/", loggingHandler(fileHandler))

	go func() {
		log.Println("Starting up at :8080")
		log.Fatal(http.ListenAndServe(":8080", nil))
	}()

	// Handle SIGTERM.
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM)
	log.Printf("Received signal '%v'. Exiting.", <-ch)
}
Exemple #13
0
func init() {
	initTemplates("./present/")
	present.PlayEnabled = true
	initPlayground("./present/", nil)

	// App Engine has no /etc/mime.types
	mime.AddExtensionType(".svg", "image/svg+xml")
}
Exemple #14
0
func init() {
	mime.AddExtensionType(".dart", "application/dart")

	fs := http.FileServer(http.Dir("app/build/web"))
	http.Handle("/", fs)
	//router.Run(":8080")
	//http.ListenAndServe(":8080", nil)
}
Exemple #15
0
// Register all the mimes in types.go
func init() {
	for _, v := range mimes {
		err := mime.AddExtensionType(v.Extension, v.Type)
		if err != nil {
			log.Println(err)
		}
	}
}
Exemple #16
0
//register the type on init
func init() {
	//we should register this mime type in our mime-type to file extension list. it really doesn't exist.
	//we'll use .tag
	mime.AddExtensionType(TAG_FILE_EXT, TAG_MIME_TYPE)

	core.RegisterType(TAG_MIME_TYPE, func() core.Inspecter {
		return &Tag{}
	})
}
Exemple #17
0
//Same as http://godoc.org/mime
func TypeByExtension(ext string) string {
	if !initd {
		for i := 0; i < len(types); i += 2 {
			mime.AddExtensionType("."+types[i], types[i+1])
		}
		initd = true
	}
	return mime.TypeByExtension(ext)
}
Exemple #18
0
func initialize() {
	mime.AddExtensionType(".css", "text/css")
	//判断初始化参数
	initArgs()

	models.Connect()

	router()
	beego.AddFuncMap("stringsToJson", StringsToJson)
}
Exemple #19
0
func main() {

	// Force logrus to use console colouring
	var forceColours = flag.Bool("logrusforcecolours", false, "force logrus to use console colouring")
	flag.Parse()
	if *forceColours {
		log.SetFormatter(&log.TextFormatter{ForceColors: true})
	}

	// What are we running on?
	log.WithFields(
		log.Fields{"gover": runtime.Version(), "goos": runtime.GOOS, "goarch": runtime.GOARCH}).Info("Brightlight")

	// Start drivers
	controller.StartTeensyDriver()
	controller.StartRelayDriver()
	renderer := make(chan *framebuffer.FrameBuffer)
	framebuffer.StartDriver(renderer)
	animations.StartDriver(renderer)
	stats.StartDriver()

	// Figure out where the content directory is GOPATH may contain : separated paths
	contentPath := path.Join(os.Getenv("GOPATH"), "src/github.com/andew42/brightlight/ui")
	log.WithField("contentPath", contentPath).Info("Serving content")

	// Set up web routes (first static content)
	mime.AddExtensionType(".manifest", "text/cache-manifest")
	fs := http.FileServer(http.Dir(contentPath))
	http.Handle("/", fs)

	// Config requires PUT (write) support
	http.HandleFunc("/config/", servers.GetConfigHandler(contentPath))

	// Requests to run zero or more animation (json payload)
	http.HandleFunc("/RunAnimations/", servers.RunAnimationsHandler)

	// Requests to show a strip length on the room lights
	http.HandleFunc("/StripLength/", servers.StripLenHandler)

	// Push frame buffer changes over a web socket
	http.Handle("/FrameBuffer", websocket.Handler(servers.FrameBufferHandler))

	// Push stats info over a web socket
	http.Handle("/Stats", websocket.Handler(servers.StatsHandler))

	// Start the option server
	http.HandleFunc("/option/", servers.OptionHandler)

	// Start web server
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Error(err.Error())
	}

	log.Info("brightlight exited")
}
Exemple #20
0
func init() {

	// Had to do this because returns svg as text/xml when running on AppEngine: http://goo.gl/hwZSp2
	mime.AddExtensionType(".svg", "image/svg+xml")

	r := mux.NewRouter()
	sr := r.PathPrefix("/api").Subrouter()
	sr.HandleFunc("/posts", Posts)
	r.HandleFunc("/{rest:.*}", handler)
	http.Handle("/", r)
}
Exemple #21
0
func configureExts() error {
	exts := map[string]string{
		".woff": "application/x-font-woff",
	}
	for ext, t := range exts {
		if err := mime.AddExtensionType(ext, t); err != nil {
			return fmt.Errorf("add extension failed: %s", err)
		}
	}
	return nil
}
Exemple #22
0
func main() {
	mime.AddExtensionType(".gz", "application/x-gzip")
	http.HandleFunc("/simple", simpleIndexHandler)
	http.HandleFunc("/simple/", simpleHandler)
	http.Handle("/file/", http.StripPrefix("/file", http.FileServer(http.Dir(FonduData))))
	http.HandleFunc("/fondu/cached-file/", cachedFileHandler)
	http.HandleFunc("/", rootHandler)
	http.HandleFunc("*", http.NotFound)
	log.Println("Starting fondu on port " + FonduPort)
	http.ListenAndServe(":"+FonduPort, nil)
}
Exemple #23
0
func init() {
	filename := filterName + ".json"
	config := new(Config)
	err := storage.LookupStoreByFilterName(filterName).UnmarshallJson(filename, config)
	if err != nil {
		glog.Fatalf("storage.ReadJsonConfig(%#v) failed: %s", filename, err)
	}

	err = filters.Register(filterName, &filters.RegisteredFilter{
		New: func() (filters.Filter, error) {
			return NewFilter(config)
		},
	})

	if err != nil {
		glog.Fatalf("Register(%#v) error: %s", filterName, err)
	}

	mime.AddExtensionType(".crt", "application/x-x509-ca-cert")
	mime.AddExtensionType(".mobileconfig", "application/x-apple-aspen-config")
}
Exemple #24
0
func NewHttp(bitTorrent *BitTorrent) *Http {
	mime.AddExtensionType(".avi", "video/avi")
	mime.AddExtensionType(".mkv", "video/x-matroska")
	mime.AddExtensionType(".mp4", "video/mp4")

	mux := routes.New()
	mux.Get("/", index)
	mux.Get("/video", video)
	mux.Get("/shutdown", shutdown)

	return &Http{
		bitTorrent: bitTorrent,
		server: &graceful.Server{
			Timeout: 500 * time.Millisecond,
			Server: &http.Server{
				Addr:    fmt.Sprintf("%v:%v", "0.0.0.0", settings.httpPort),
				Handler: mux,
			},
		},
	}
}
Exemple #25
0
// Function is a mirror of http://godoc.org/mime#TypeByExtension but adds extra
// extensions before checking.
func TypeByExtension(ext string) string {
	// Lock the mutex while we add the extra extensions so multiple threads
	// don't try and add the extra extensions at the same time.
	mutex.Lock()
	if !initialized {
		for i := 0; i < len(types); i += 2 {
			mime.AddExtensionType("."+types[i], types[i+1])
		}
		initialized = true
	}
	mutex.Unlock()

	return mime.TypeByExtension(ext)
}
Exemple #26
0
func init() {
	mime.AddExtensionType(METAFILE_EXT, METAFILE_MIME)

	RegisterStore("fs-store", func(c *ServiceConfig, s *Service) (Store, error) {
		store, ok := c.Conf["path"]
		if !ok {
			store = fsStoreDEFAULT_PATH
		}
		fs_store, ok := store.(string)
		if !ok {
			return nil, fmt.Errorf("FS-Store Config `path` must be a string value: got `%v` (%T)", store, store)
		}
		return FileSystemStore(ExpandHome(fs_store)), nil
	})
}
func initialize() {

	mime.AddExtensionType(".css", "text/css")

	args := os.Args
	for _, v := range args {
		if v == "InitDB" {
			// 创建表 插入数据等等,只在执行./CStore InitDB 时候执行一次
			models.InitDB()
			os.Exit(0)
		}
	}
	// 链接数据库
	models.Connect()
}
func bootstrap() {

	mime.AddExtensionType(".md", "text/markdown")

	v, err := Asset("_static/version")
	if err != nil {
		log.Printf("[ WARN ] server version not found, wrong build")
	} else {
		SERVER_VERSION = strings.TrimSpace(string(v))
	}

	templates = make(map[string]*template.Template)

	pages := []string{"view", "listdir", "history", "diff", "edit"}
	for _, element := range pages {
		data, err := Asset("_static/" + element + ".html")
		if err != nil {
			log.Fatalf("fail to load the %s.html", element)
		}
		templates[element], err = template.New(element).Parse(string(data))
		if err != nil {
			log.Fatalf("cannot parse %s template", element)
		}
	}

	if len(wikiConfig.root) > 0 {
		// we should chdir to the root
		err := os.Chdir(wikiConfig.root)
		if err != nil {
			log.Fatal(err)
			os.Exit(1)
		}
		log.Printf("chdir to the '%s'", wikiConfig.root)
	}
	if wikiConfig.init {
		if repo, err := git.OpenRepository("."); err != nil {
			_, err := git.InitRepository(".", false)
			if err != nil {
				log.Fatal(err)
				os.Exit(1)
			}
			log.Printf("git init finished at .")
		} else {
			log.Printf("git repository already found, skip git init")
			repo.Free()
		}
	}
}
Exemple #29
0
func main() {
	flag.Parse()

	// Had to do this because returns svg as text/xml when running on AppEngine: http://goo.gl/hwZSp2
	mime.AddExtensionType(".svg", "image/svg+xml")

	r := mux.NewRouter()
	apiServer, err := url.Parse("http://localhost:8183")
	if err != nil {
		log.Fatal(err)
	}
	r.Handle("/api/{rest:.*}", httputil.NewSingleHostReverseProxy(apiServer))
	r.HandleFunc("/{rest:.*}", staticHandler)
	http.Handle("/", r)
	log.Printf("Listening on %s", *addr)
	log.Fatal(http.ListenAndServe(*addr, nil))
}
Exemple #30
0
func main() {

	// Had to do this because returns svg as text/xml when running on AppEngine: http://goo.gl/hwZSp2
	mime.AddExtensionType(".svg", "image/svg+xml")
	db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
	if err != nil {
		log.Fatal(err)
	}
	db.CreateTable(&User{})
	s := &server{db}

	r := mux.NewRouter()
	sr := r.PathPrefix("/api").Subrouter()
	sr.HandleFunc("/register", s.registerHandler)
	r.HandleFunc("/{rest:.*}", s.staticHandler)
	http.Handle("/", r)
	log.Fatal(http.ListenAndServe(":8182", nil))
}