Golang StripPrefix示例

说明

golang stripprefix示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: http_json_server.go 项目: arubenis/golightify

func NewLightifyServer(lightifyAddr string) error {

	err := golightify.NewLightifyBridge(lightifyAddr)
	if err != nil {
		log.Printf("Connection to lightify bridge failed: ", err.Error())
		return err
	}

	mux := http.NewServeMux()
	server := &http.Server{
		Addr:    ":8080",
		Handler: mux,
	}
	mux.HandleFunc("/api/lights", lightsHandler)
	mux.HandleFunc("/api/groups", groupsHandler)
	mux.Handle("/api/lights/", http.StripPrefix("/api/lights/", lightHandler{}))
	mux.Handle("/api/groups/", http.StripPrefix("/api/groups/", groupHandler{}))

	log.Println("Listening... ", server.Addr)
	err = server.ListenAndServe()
	if err != nil {
		log.Printf("Server failed: ", err.Error())
		return err
	}

	return nil
}

示例#2
文件: apiserver.go 项目: kleopatra999/kubernetes

// New creates a new APIServer object.
// 'storage' contains a map of handlers.
// 'prefix' is the hosting path prefix.
func New(storage map[string]RESTStorage, prefix string) *APIServer {
	s := &APIServer{
		storage: storage,
		prefix:  strings.TrimRight(prefix, "/"),
		ops:     NewOperations(),
		mux:     http.NewServeMux(),
		// Delay just long enough to handle most simple write operations
		asyncOpWait: time.Millisecond * 25,
	}

	// Primary API methods
	s.mux.HandleFunc(s.prefix+"/", s.handleREST)
	s.mux.HandleFunc(s.watchPrefix()+"/", s.handleWatch)

	// Support services for the apiserver
	s.mux.Handle("/logs/", http.StripPrefix("/logs/", http.FileServer(http.Dir("/var/log/"))))
	healthz.InstallHandler(s.mux)
	s.mux.HandleFunc("/version", handleVersion)
	s.mux.HandleFunc("/", handleIndex)

	// Handle both operations and operations/* with the same handler
	s.mux.HandleFunc(s.operationPrefix(), s.handleOperation)
	s.mux.HandleFunc(s.operationPrefix()+"/", s.handleOperation)

	// Proxy minion requests
	s.mux.Handle("/proxy/minion/", http.StripPrefix("/proxy/minion", http.HandlerFunc(handleProxyMinion)))

	return s
}

示例#3
文件: example.go 项目: alytvynov/goa

func main() {
	if err := goa.Init(goa.Config{
		LoginPage:     "/login.html",
		HashKey:       []byte(hashKey),
		EncryptionKey: []byte(cryptoKey),
		CookieName:    "session",
		PQConfig:      "user=test_user password=test_pass dbname=goa",
	}); err != nil {
		log.Println(err)
		return
	}

	// public (no-auth-required) files
	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	// protected files, only for logged-in users
	http.Handle("/protected/", goa.NewHandler(http.StripPrefix("/protected/", http.FileServer(http.Dir("protected")))))
	// home handler
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "index.html")
	})
	http.HandleFunc("/login.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "login.html")
	})
	http.HandleFunc("/register.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "register.html")
	})

	if err := http.ListenAndServeTLS(":8080", "keys/cert.pem", "keys/key.pem", nil); err != nil {
		log.Println(err)
	}
}

示例#4
文件: irwin-server.go 项目: paulgrock/ipl-irwin

func main() {

	var portNumber int
	flag.IntVar(&portNumber, "port", 80, "Default port is 80")
	flag.Parse()

	// Routes to serve front-end assets
	r := mux.NewRouter()
	http.Handle("/javascripts/", http.StripPrefix("/javascripts/", http.FileServer(http.Dir("frontend/public/javascripts/"))))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("frontend/public/images/"))))
	http.Handle("/stylesheets/", http.StripPrefix("/stylesheets/", http.FileServer(http.Dir("frontend/public/stylesheets/"))))

	// API Endpoints
	r.PathPrefix(V1_PREFIX + "/run-ad-on/{service}/for/{stream}").HandlerFunc(ads.AdRequester)
	r.Path(V1_PREFIX + "/ping").HandlerFunc(health.Ping)

	// Pass to front-end
	r.PathPrefix(V1_PREFIX + "/stream").HandlerFunc(index)
	r.PathPrefix(V1_PREFIX).HandlerFunc(index)

	http.Handle("/", r)
	port := strconv.FormatInt(int64(portNumber), 10)
	fmt.Println("IRWIn Server starting")
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Could not start on port "+port, err)
	}
}

示例#5
文件: server.go 项目: Juerd/Up1

func main() {
	http.HandleFunc("/", index)
	http.HandleFunc("/up", upload)
	http.HandleFunc("/del", delfile)
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("static"))))
	http.Handle("/i/", http.StripPrefix("/i", http.FileServer(http.Dir("i"))))

	config = readConfig()
	validateConfig(config)

	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		defer wg.Done()
		if config.Http.Enabled {
			log.Printf("Starting HTTP server on %s\n", config.Http.Listen)
			log.Println(http.ListenAndServe(config.Http.Listen, nil))
		}
	}()

	go func() {
		defer wg.Done()
		if config.Https.Enabled {
			log.Printf("Starting HTTPS server on %s\n", config.Https.Listen)
			log.Println(http.ListenAndServeTLS(config.Https.Listen, config.Https.Cert, config.Https.Key, nil))
		}
	}()

	wg.Wait()
}

示例#6
文件: apiserver.go 项目: hungld/kubernetes

// InstallSupport registers the APIServer support functions into a mux.
func InstallSupport(mux mux) {
	healthz.InstallHandler(mux)
	mux.Handle("/logs/", http.StripPrefix("/logs/", http.FileServer(http.Dir("/var/log/"))))
	mux.Handle("/proxy/minion/", http.StripPrefix("/proxy/minion", http.HandlerFunc(handleProxyMinion)))
	mux.HandleFunc("/version", handleVersion)
	mux.HandleFunc("/", handleIndex)
}

示例#7
文件: susi-webstack.go 项目: webvariants/susi-gowebstack

func main() {
	flag.Parse()
	s, err := susigo.NewSusi(*susiaddr, *cert, *key)
	if err != nil {
		log.Printf("Error while creating susi connection: %v", err)
		return
	}
	susi = s
	log.Println("successfully create susi connection")
	sessionTimeouts = make(map[string]time.Time)

	if *user == "" && *pass == "" {
		http.HandleFunc("/publish", publishHandler)
		http.HandleFunc("/upload", uploadHandler)
		http.Handle("/ws", websocket.Handler(websocketHandler))
		http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))))
		http.HandleFunc("/", redirectToIndex)
	} else {
		http.HandleFunc("/publish", BasicAuth(publishHandler))
		http.HandleFunc("/upload", BasicAuth(uploadHandler))
		http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP))
		http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP))
		http.HandleFunc("/", BasicAuth(redirectToIndex))
	}

	log.Printf("starting http server on %v...", *webaddr)
	if *useHTTPS {
		log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux)))
	} else {
		log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux)))
	}
}

示例#8
文件: hidemyemail.go 项目: katasonov/hidemyemail

func main() {

	err := LoadConfig()
	if err != nil {
		log.Fatal("Could not load config file hidemyemail.cfg")
		return
	}

	g_conn_string = g_config.DbConnectionString

	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(g_config.ResourcePath+"/images"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir(g_config.ResourcePath+"/css"))))
	http.HandleFunc("/add",
		func(w http.ResponseWriter, r *http.Request) {
			handleAdd(w, r)
		})
	http.HandleFunc("/get",
		func(w http.ResponseWriter, r *http.Request) {
			handleGet(w, r)
		})
	http.HandleFunc("/",
		func(w http.ResponseWriter, r *http.Request) {
			handleGetCaptcha(w, r)
		})
	log.Fatal(http.ListenAndServe(":"+g_config.Port, nil))
}

示例#9
文件: main.go 项目: nav01/CSCI-130

func main() {
	//Have to add handles for serving static pages, still a bit fuzzy on the FileServer stuff.
	http.Handle("/pic/", http.StripPrefix("/pic/", http.FileServer(http.Dir("pic"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.HandleFunc("/", handleThis)
	http.ListenAndServe(":8000", nil)
}

示例#10
文件: server.go 项目: klenin/orc

func main() {
	db.DB, err = sql.Open("postgres", config.GetValue("DATABASE_URL"))
	defer db.DB.Close()

	if err != nil {
		log.Fatalln("Error DB open:", err.Error())
	}

	if err = db.DB.Ping(); err != nil {
		log.Fatalln("Error DB ping:", err.Error())
	}

	log.Println("Connected to DB")

	testData := flag.Bool("test-data", false, "to load test data")
	resetDB := flag.Bool("reset-db", false, "reset the database")
	flag.Parse()

	initial.Init(*resetDB, *testData)

	// base := new(controllers.BaseController)
	// base.Index().LoadContestsFromCats()

	http.Handle("/", new(router.FastCGIServer))
	http.HandleFunc("/wellcometoprofile/", controllers.WellcomeToProfile)
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./static/js"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./static/css"))))
	http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("./static/img"))))

	addr := config.GetValue("HOSTNAME") + ":" + config.GetValue("PORT")
	log.Println("Server listening on", addr)
	log.Fatalln("Error listening:", http.ListenAndServe(addr, nil))
}

示例#11
文件: main.go 项目: DiscoViking/blog

func main() {
	fs := filesystem.New("articles")
	recv := make(chan request, 5)
	for i := 0; i < 4; i++ {
		go handleRequests(fs, recv)
	}

	// Serve websocket article requests.
	http.HandleFunc("/ws", serveWs(recv))

	// Serve http article requests.
	articleHandler := httpArticleHandler{recv}
	http.Handle("/article/", http.StripPrefix("/article/", &articleHandler))

	// Serve front page.
	http.HandleFunc("/",
		func(w http.ResponseWriter, req *http.Request) {
			http.ServeFile(w, req, "front.html")
		})

	// Serve static content.
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./css"))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./js"))))
	http.Handle("/fonts/", http.StripPrefix("/fonts/", http.FileServer(http.Dir("./fonts"))))
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}

示例#12
文件: server.go 项目: sjtlqy/Go

func main() {
	if len(os.Args) != 2 {
		fmt.Fprint(os.Stderr, "Usage: ", os.Args[0], ":port\n")
		os.Exit(1)
	}
	port := os.Args[1]

	// dictionaryPath := "/var/www/go/chinese/cedict_ts.u8"
	dictionaryPath := "cedict_ts.u8"
	d = new(dictionary.Dictionary)
	d.Load(dictionaryPath)
	fmt.Println("Loaded dict", len(d.Entries))

	http.HandleFunc("/", listFlashCards)
	//fileServer := http.FileServer("/var/www/go/chinese/jscript", "/jscript/")
	fileServer := http.StripPrefix("/jscript/", http.FileServer(http.Dir("jscript")))
	http.Handle("/jscript/", fileServer)
	// fileServer = http.FileServer("/var/www/go/chinese/html", "/html/")
	fileServer = http.StripPrefix("/html/", http.FileServer(http.Dir("html")))
	http.Handle("/html/", fileServer)

	http.HandleFunc("/wordlook", lookupWord)
	http.HandleFunc("/flashcards.html", listFlashCards)
	http.HandleFunc("/flashcardSets", manageFlashCards)
	http.HandleFunc("/searchWord", searchWord)
	http.HandleFunc("/addWord", addWord)
	http.HandleFunc("/newFlashCardSet", newFlashCardSet)

	// deliver requests to the handlers
	err := http.ListenAndServe(port, nil)
	checkError(err)
	// That's it!
}

示例#13
文件: httpsrv.go 项目: yschu7/go_test

func main() {
	http.HandleFunc("/hello", hello)
	http.Handle(
		"/example/",
		http.StripPrefix(
			"/example/",
			http.FileServer(http.Dir("example")),
		),
	)
	http.Handle(
		"/chksum/",
		http.StripPrefix(
			"/chksum/",
			http.FileServer(http.Dir("chksum")),
		),
	)
	http.Handle(
		"/all/",
		http.StripPrefix(
			"/all/",
			http.FileServer(http.Dir(".")),
		),
	)
	http.ListenAndServe(":9000", nil)
}

示例#14
文件: main.go 项目: mjrmyke/GoLangCourse

func init() {
	//html files, and strips prefixes for img and css
	tpl, _ = template.ParseGlob("*.html")
	http.HandleFunc("/", main)
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img"))))
}

示例#15
文件: dashr.go 项目: vdesjardins/ansible-dashr

func main() {
	dashr_ip := flag.String("fqdn", "127.0.0.1", "IP/FQDN to run HTTP listener at")
	dashr_port := flag.String("http", "8001", "port to run HTTP listener at")
	www_data := flag.String("www", "www-data", "path to ansible dashr static site content")
	ansible_setup := flag.String("ansible", "dummy-ansible-files", "path to ansible setup root of Playbooks, Roles Dir")
	dashr_config := flag.String("config", "config", "path to fetch/save Config used by Static Site Content")
	flag.Parse()

	connection_string := fmt.Sprintf("%s:%s", *dashr_ip, *dashr_port)
	www_data_uri := fmt.Sprintf("/%s/", *www_data)
	ansible_setup_uri := fmt.Sprintf("/%s/", *ansible_setup)
	dashr_config_uri := fmt.Sprintf("/%s/", *dashr_config)

	dashr_fs := http.FileServer(http.Dir(*www_data))
	http.Handle(www_data_uri, http.StripPrefix(www_data_uri, dashr_fs))

	ansible_fs := http.FileServer(http.Dir(*ansible_setup))
	http.Handle(ansible_setup_uri, http.StripPrefix(ansible_setup_uri, ansible_fs))

	config_fs := http.FileServer(http.Dir(*dashr_config))
	http.Handle(dashr_config_uri, http.StripPrefix(dashr_config_uri, config_fs))

	http.HandleFunc("/", redirect)
	log.Println("Ansible Dashr @", connection_string)
	if err := http.ListenAndServe(connection_string, nil); err != nil {
		fmt.Println("ERROR: Failed to start server.", err.Error())
	}
}

示例#16
文件: web_program.go 项目: josephlewis42/autopilot

func main() {

	err := GenerateFolders()
	fmt.Println(err)

	includepath, _ := filepath.Abs("./static/")

	http.Handle("/inc/", http.StripPrefix("/inc/", http.FileServer(http.Dir(includepath))))
	http.HandleFunc("/log/download/", AutopilotDownloader)
	http.HandleFunc("/log/delete/", GenericDeleter("./autopilot/runs/"))
	http.HandleFunc("/autopilot/upload/", GenericUploader("./autopilot/pilots/"))
	http.HandleFunc("/autopilot/delete/", GenericDeleter("./autopilot/pilots/"))
	http.HandleFunc("/autopilot/start/", StartAutopilot)
	http.HandleFunc("/autopilot/stop/", StopAutopilot)
	http.HandleFunc("/configuration/upload/", GenericUploader("./autopilot/configurations/"))
	http.HandleFunc("/configuration/delete/", GenericDeleter("./autopilot/configurations/"))
	http.HandleFunc("/configuration/edit/", EditConfiguration)
	http.HandleFunc("/command/shutdown/", GenericCommand("/sbin/shutdown", "-H", "-P", "now"))
	http.HandleFunc("/command/proc/", GenericCommand("/bin/ps", "-aux"))
	http.HandleFunc("/command/ifconfig/", GenericCommand("/sbin/ifconfig"))
	http.HandleFunc("/command/dmesg/", GenericCommand("/bin/dmesg"))
	http.HandleFunc("/command/w/", GenericCommand("/usr/bin/w"))
	http.HandleFunc("/command/cpuinfo/", GenericCommand("/bin/cat", "/proc/cpuinfo"))

	http.Handle("/configuration/download/", http.StripPrefix("/configuration/download/", http.FileServer(http.Dir("./autopilot/configurations/"))))
	http.Handle("/autopilot/download/", http.StripPrefix("/autopilot/download/", http.FileServer(http.Dir("./autopilot/pilots/"))))

	http.HandleFunc("/", rootHandler)

	fmt.Println("Running")
	err = http.ListenAndServe("localhost:9000", nil)
	fmt.Println(err)
}

示例#17
文件: app.go 项目: geoct826/goblog

func init() {
	r := mux.NewRouter()

	apiGet := r.PathPrefix("/api").Methods("GET").Subrouter()
	apiGet.HandleFunc("/{view}", apiController.ApiGetHandler)
	apiGet.HandleFunc("/{view}/{key}", apiController.ApiGetHandler)
	apiGet.HandleFunc("/{view}/{parent}/{key}", apiController.ApiGetHandler)

	apiPost := r.PathPrefix("/api").Methods("POST").Subrouter()
	apiPost.HandleFunc("/{view}", apiController.ApiPostHandler)
	apiPost.HandleFunc("/{view}/{key}", apiController.ApiPostHandler)

	apiDelete := r.PathPrefix("/api").Methods("DELETE").Subrouter()
	apiDelete.HandleFunc("/{view}/{key}", apiController.ApiDeleteHandler)

	r.PathPrefix("/admin/").Handler(http.StripPrefix("/admin/", http.FileServer(http.Dir("./static/admin"))))
	r.PathPrefix("/admin").Handler(http.RedirectHandler("/admin/", 301))

	r.PathPrefix("/blog").Handler(http.StripPrefix("/blog", http.FileServer(http.Dir("./static"))))

	r.PathPrefix("/foundation/").Handler(http.StripPrefix("/foundation/", http.FileServer(http.Dir("./static/foundation"))))

	r.HandleFunc("/{.path:.*}", cloudAdminHandler).Methods("GET")
	r.HandleFunc("/{.path:.*}", cloudAdminPostHandler).Methods("POST")

	http.Handle("/", r)
}

示例#18
文件: webserver.go 项目: nyxtom/usda

func (server *WebServer) listen() {
	if server.httpServer.FileDescriptor == 0 {
		server.LogInfoF("listening on %s", server.httpServer.Addr)
	} else {
		server.LogInfoF("listening on existing file descriptor %d, %s", server.httpServer.FileDescriptor, server.httpServer.Addr)
	}

	handleFunc("/", server.logReq, server.index)
	//handleFunc("/restart", server.logReq, server.restart)
	//handleFunc("/shutdown", server.logReq, server.shutdown)
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./app/css"))))
	http.Handle("/imgs/", http.StripPrefix("/imgs/", http.FileServer(http.Dir("./app/imgs"))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./app/js"))))
	items := []string{"apple-touch-icon.png", "crossdomain.xml", "favicon.ico", "humans.txt", "robots.txt", "tile-wide.png", "tile.png", "browserconfig.xml"}
	for _, k := range items {
		handleFunc("/"+k, server.logReq, func(w http.ResponseWriter, req *http.Request) {
			http.ServeFile(w, req, "./"+k)
		})
	}

	err := server.httpServer.ListenAndServe()
	if err != nil {
		server.LogErr(err)
		server.Close()
	}
}

示例#19
文件: main.go 项目: ph3ng/CSCI-130-Spring-16

func init() {
	http.HandleFunc("/", handler)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css/"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img/"))))
	tpl = template.Must(template.ParseGlob("*.html"))
}

示例#20
文件: main.go 项目: bamnet/shuttle_tracking_2

func main() {
	// close Mongo session when server terminates
	defer App.Session.Close()

	// Start auto updater
	go App.UpdateShuttles(Config.DataFeed, Config.UpdateInterval)

	// Routing
	r := mux.NewRouter()
	r.HandleFunc("/", IndexHandler).Methods("GET")
	r.HandleFunc("/admin", AdminHandler).Methods("GET")
	r.HandleFunc("/admin/{*}", AdminHandler).Methods("GET")
	r.HandleFunc("/vehicles", App.VehiclesHandler).Methods("GET")
	r.HandleFunc("/vehicles/create", App.VehiclesCreateHandler).Methods("POST")
	r.HandleFunc("/updates", App.UpdatesHandler).Methods("GET")
	r.HandleFunc("/routes", App.RoutesHandler).Methods("GET")
	r.HandleFunc("/routes/create", App.RoutesCreateHandler).Methods("POST")
	r.HandleFunc("/stops", App.StopsHandler).Methods("GET")
	r.HandleFunc("/stops/create", App.StopsCreateHandler).Methods("POST")
	// Static files
	r.PathPrefix("/bower_components/").Handler(http.StripPrefix("/bower_components/", http.FileServer(http.Dir("bower_components/"))))
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	// Serve requests
	http.Handle("/", r)
	if err := http.ListenAndServe(":8080", r); err != nil {
		log.Fatalf("Unable to ListenAndServe: %v", err)
	}
}

示例#21
文件: handler.go 项目: davelondon/tchaik

// NewHandler creates the root http.Handler.
func NewHandler(l Library, hs history.Store, mediaFileSystem, artworkFileSystem store.FileSystem) http.Handler {
	var c httpauth.Checker = httpauth.None{}
	if authUser != "" {
		c = httpauth.Creds(map[string]string{
			authUser: authPassword,
		})
	}
	h := fsServeMux{
		httpauth.NewServeMux(c, http.NewServeMux()),
	}

	h.HandleFunc("/", rootHandler)
	h.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir))))

	mediaFileSystem = l.FileSystem(mediaFileSystem)
	artworkFileSystem = l.FileSystem(artworkFileSystem)
	h.HandleFileSystem("/track/", mediaFileSystem)
	h.HandleFileSystem("/artwork/", artworkFileSystem)
	h.HandleFileSystem("/icon/", store.FaviconFileSystem(artworkFileSystem))

	p := newPlayers()
	h.Handle("/socket", NewWebsocketHandler(l, p, hs))
	h.Handle("/api/players/", http.StripPrefix("/api/players/", &playersHandler{p}))

	return h
}

示例#22
文件: main.go 项目: bpeng/walking-md

func init() {
	if templates == nil {
		templates = make(map[string]*template.Template)
	}
	templates["index"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/index.tmpl"))
	templates["index1"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/index1.tmpl"))
	templates["edit"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/edit.tmpl"))
	templates["preview"] = template.Must(template.ParseFiles("tmpl/preview.tmpl"))

	//handle image/css and generated html files
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.Handle("/_images/", http.StripPrefix("/_images/", http.FileServer(http.Dir("_images"))))
	http.Handle("/_html/", http.StripPrefix("/_html/", http.FileServer(http.Dir("_html"))))
	http.Handle("/_html/_images/", http.StripPrefix("/_html/_images/", http.FileServer(http.Dir("_html/_images"))))
	http.Handle("/_html/css", http.StripPrefix("/_html/css", http.FileServer(http.Dir("_html/css"))))

	// set up html options
	htmlExt = 0
	htmlExt |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
	htmlExt |= blackfriday.EXTENSION_TABLES
	htmlExt |= blackfriday.EXTENSION_FENCED_CODE
	htmlExt |= blackfriday.EXTENSION_AUTOLINK
	htmlExt |= blackfriday.EXTENSION_STRIKETHROUGH
	htmlExt |= blackfriday.EXTENSION_SPACE_HEADERS

	htmlFlags = blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES |
		blackfriday.HTML_FOOTNOTE_RETURN_LINKS |
		blackfriday.HTML_SMARTYPANTS_ANGLED_QUOTES

}

示例#23
文件: main.go 项目: ChrisKaufmann/feedinator-go

func main() {
	defer db.Close()
	http.HandleFunc("/main", handleMain)
	http.HandleFunc("/demo", handleDemo)
	http.HandleFunc("/logout", auth.HandleLogout)
	http.HandleFunc("/authorize", auth.HandleAuthorize)
	http.HandleFunc("/oauth2callback", auth.HandleOAuth2Callback)
	http.HandleFunc("/categoryList/", handleCategoryList)
	http.HandleFunc("/category/", handleCategory)
	http.HandleFunc("/feed/list/", handleFeedList)
	http.HandleFunc("/feed/new/", handleNewFeed)
	http.HandleFunc("/feed/", handleFeed)
	http.HandleFunc("/entry/mark/", handleMarkEntry)
	http.HandleFunc("/entry/", handleEntry)
	http.HandleFunc("/entries/", handleEntries)
	http.HandleFunc("/menu/select/", handleSelectMenu)
	http.HandleFunc("/menu/", handleMenu)
	http.HandleFunc("/stats/", handleStats)
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	http.Handle("/favicon.ico", http.StripPrefix("/favicon.ico", http.FileServer(http.Dir("./static/favicon.ico"))))
	http.HandleFunc("/", handleRoot)

	go feed.CacheAllCats()  //create cache for categories at startup
	go feed.CacheAllFeeds() //create cache for feeds at startup
	print("Listening on 127.0.0.1:" + port + "\n")
	http.ListenAndServe("127.0.0.1:"+port, nil)
}

示例#24
文件: main.go 项目: computermatt/QSL-Card-Showcase

func main() {
	parseConstants()
	PrefixLookup.LoadPrefixes()

	file, e := ioutil.ReadFile(qsoFile)
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	json.Unmarshal(file, &qsls)

	listOfContactedCountries = getListOfCountries()
	listOfContactsPerCountry = getContactsPerCountry()
	http.Handle("/compressedCards/", http.StripPrefix("/compressedCards",
		http.FileServer(http.Dir(path.Join(rootdir, convertedFolder)))))
	http.Handle("/thumbnails/", http.StripPrefix("/thumbnails",
		http.FileServer(http.Dir(path.Join(rootdir, resizedFolder)))))
	http.Handle("/cards/", http.StripPrefix("/cards",
		http.FileServer(http.Dir(path.Join(rootdir, cardsFolder)))))
	http.Handle("/images/", http.StripPrefix("/images",
		http.FileServer(http.Dir(path.Join(rootdir, imagesFolder)))))
	http.Handle("/html/", http.StripPrefix("/html",
		http.FileServer(http.Dir(path.Join(rootdir, "/html")))))

	http.HandleFunc("/", index)
	http.HandleFunc("/browse/", browse)
	http.HandleFunc("/country/", browseCountry)
	http.HandleFunc("/view/", displayCard)
	http.HandleFunc("/api/", apiGetCall)

	fmt.Printf("Web Server started\n")
	http.ListenAndServe(":8080", nil)
}

示例#25
文件: gitserver.go 项目: cjnygard/origin

func Start(config *Config) error {
	if err := clone(config); err != nil {
		return err
	}
	handler := handler(config)

	ops := http.NewServeMux()
	if config.AllowHooks {
		ops.Handle("/hooks/", prometheus.InstrumentHandler("hooks", http.StripPrefix("/hooks", hooksHandler(config))))
	}
	/*ops.Handle("/reflect/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()
		fmt.Fprintf(os.Stdout, "%s %s\n", r.Method, r.URL)
		io.Copy(os.Stdout, r.Body)
	}))*/
	ops.Handle("/metrics", prometheus.UninstrumentedHandler())
	healthz.InstallHandler(ops)

	mux := http.NewServeMux()
	mux.Handle("/", prometheus.InstrumentHandler("git", handler))
	mux.Handle("/_/", http.StripPrefix("/_", ops))

	log.Printf("Serving %s on %s", config.Home, config.Listen)
	return http.ListenAndServe(config.Listen, mux)
}

示例#26
文件: dashboard.go 项目: andrewcharlton/school-dashboard

func main() {

	// Get Hostname
	host, err := getHost()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("School dashboard started.\nConnect at: %v:8080", host)

	// Get database filename
	args := flag.Args()
	filename := "school.db"
	if len(args) >= 1 {
		filename = args[1]
	}

	// Connect to database
	env, err := env.Connect(filename)
	if err != nil {
		log.Fatal(err)
	}

	// Static and Image servers
	static := http.FileServer(http.Dir("./static"))
	images := http.FileServer(http.Dir("./images"))

	// Client Server
	clientMux := http.NewServeMux()
	clientMux.Handle("/static/", http.StripPrefix("/static/", static))
	clientMux.Handle("/images/", http.StripPrefix("/images/", images))
	clientMux.HandleFunc("/", handlers.Index(env))
	clientMux.HandleFunc("/attainmentgroups/", handlers.AttainmentGroups(env))
	clientMux.HandleFunc("/attendance/", handlers.AttendanceExplorer(env))
	clientMux.HandleFunc("/attendancegroups/", handlers.AttendanceGroups(env))
	clientMux.HandleFunc("/basics/", handlers.EnglishAndMaths(env))
	clientMux.HandleFunc("/ebacc/", handlers.EBacc(env))
	clientMux.HandleFunc("/ks3summary/", handlers.KS3Summary(env))
	clientMux.HandleFunc("/ks3groups/", handlers.KS3Groups(env))
	clientMux.HandleFunc("/progress8/", handlers.Progress8(env))
	clientMux.HandleFunc("/progress8groups/", handlers.Progress8Groups(env))
	//clientMux.HandleFunc("/export/headlines/", handlers.ExportHeadlines(env))
	clientMux.HandleFunc("/export/subject/", handlers.ExportSubject(env))
	clientMux.HandleFunc("/subjects/", handlers.SubjectOverview(env))
	clientMux.HandleFunc("/progressgrid/", handlers.ProgressGrid(env))
	clientMux.HandleFunc("/subjectgroups/", handlers.SubjectGroups(env))
	clientMux.HandleFunc("/student/", handlers.Student(env))
	clientMux.HandleFunc("/search/", handlers.Search(env))
	for {
		err := http.ListenAndServe(":8080", clientMux)
		log.Println(err)
	}

	/*
		adminMux := http.NewServeMux()
		adminMux.Handle("/static/", http.StripPrefix("/static/", static))
		adminMux.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello") })
		http.ListenAndServe(":8081", adminMux)
	*/

}

示例#27
文件: phoneSocketServer.go 项目: ntasfi/phoneSocket

func main() {
	fmt.Println("Server address is", myAddress)
	var serverURI = fmt.Sprintf("%s:%d", configuration.ServerAddress, configuration.ServerPort)
	var isMobile = regexp.MustCompile(`(M|m)obile|(I|i)P(hone|od|ad)|(A|a)ndroid|(B|b)lackBerry|(I|i)EMobile|(K|k)indle|(N|n)etFront|(S|s)ilk-Accelerated|(hpw|web)OS|(F|f)ennec|(M|m)inimo|(O|o)pera (M|m)(obi|ini)|(B|b)lazer|(D|d)olfin|(D|d)olphin|(S|s)kyfire|(Z|z)une`)

	//communcation settings
	var newLobbyChan = make(chan *lobby)         //all the new lobbies are sent over this to our hub to be registered
	var socketConnChan = make(chan socketEntity) //the sockets send a channel to the hub with ID for their connection.
	var killHubChan = make(chan entity)          //used to kill lobbies etc off. This is sockets to lobby ONLY.

	go hub(newLobbyChan, socketConnChan, killHubChan) //spawn hub to keep track of the lobbies and answer queries about lobbies

	http.Handle(configuration.HTTPRoutes.Root, http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			if isMobile.MatchString(r.UserAgent()) { //if its a mobile user
				handleMobile(w, r)
			} else {
				handleDesktop(newLobbyChan, w, r)
			}

		}))

	http.Handle(configuration.HTTPRoutes.Javascript.Route, http.StripPrefix(configuration.HTTPRoutes.Javascript.Route, http.FileServer(http.Dir(configuration.HTTPRoutes.Javascript.RootLocation))))
	http.Handle(configuration.HTTPRoutes.Images.Route, http.StripPrefix(configuration.HTTPRoutes.Images.Route, http.FileServer(http.Dir(configuration.HTTPRoutes.Images.RootLocation))))

	http.Handle(configuration.HTTPRoutes.Websocket, websocket.Handler(
		func(ws *websocket.Conn) {
			handleSocket(socketConnChan, killHubChan, ws)
		}))

	fmt.Println("Binding and listening on", serverURI)
	if err := http.ListenAndServe(serverURI, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

示例#28
文件: web-router.go 项目: hackintoshrao/minio

// registerWebRouter - registers web router for serving minio browser.
func registerWebRouter(mux *router.Router, web *webAPIHandlers) {
	// Initialize a new json2 codec.
	codec := json2.NewCodec()

	// Minio browser router.
	webBrowserRouter := mux.NewRoute().PathPrefix(reservedBucket).Subrouter()

	// Initialize json rpc handlers.
	webRPC := jsonrpc.NewServer()
	webRPC.RegisterCodec(codec, "application/json")
	webRPC.RegisterCodec(codec, "application/json; charset=UTF-8")
	webRPC.RegisterService(web, "Web")

	// RPC handler at URI - /minio/webrpc
	webBrowserRouter.Methods("POST").Path("/webrpc").Handler(webRPC)
	webBrowserRouter.Methods("PUT").Path("/upload/{bucket}/{object:.+}").HandlerFunc(web.Upload)
	webBrowserRouter.Methods("GET").Path("/download/{bucket}/{object:.+}").Queries("token", "{token:.*}").HandlerFunc(web.Download)

	// Add compression for assets.
	compressedAssets := handlers.CompressHandler(http.StripPrefix(reservedBucket, http.FileServer(assetFS())))

	// Serve javascript files and favicon from assets.
	webBrowserRouter.Path(fmt.Sprintf("/{assets:[^/]+.js|%s}", specialAssets)).Handler(compressedAssets)

	// Serve index.html for rest of the requests.
	webBrowserRouter.Path("/{index:.*}").Handler(indexHandler{http.StripPrefix(reservedBucket, http.FileServer(assetFS()))})
}

示例#29
文件: main.go 项目: Onills/CS130

func main() {
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.Handle("/pic/", http.StripPrefix("/pic/", http.FileServer(http.Dir("pic"))))

	http.HandleFunc("/", surfer)
	http.ListenAndServe(":8080", nil)
}

示例#30
文件: plat.go 项目: navy1125/gameauth

func InitPlat() {
	http.Handle("/zssj/js/", http.StripPrefix("/zssj/js/", http.FileServer(http.Dir(config.GetConfigStr("bw_plugin")+"/js"))))
	http.Handle("/zssj/images/", http.StripPrefix("/zssj/images/", http.FileServer(http.Dir(config.GetConfigStr("bw_plugin")+"/images"))))
	for key, val := range platMap {
		http.HandleFunc(key, val)
	}
}

展开阅读全文