當前位置: 首頁>>代碼示例>>Golang>>正文


Golang http.Handle函數代碼示例

本文整理匯總了Golang中net/http.Handle函數的典型用法代碼示例。如果您正苦於以下問題:Golang Handle函數的具體用法?Golang Handle怎麽用?Golang Handle使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Handle函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {
	flag.Parse()

	if arguments.pprof {
		log.Println("pprof enabled")
		go func() {
			log.Println(http.ListenAndServe("localhost:6060", nil))
		}()

		fp, err := os.Create("backend.pprof")
		if err != nil {
			panic(err)
		}
		defer fp.Close()

		pprof.StartCPUProfile(fp)
		defer pprof.StopCPUProfile()
	}

	if err := loadTree(arguments.tree); err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	http.Handle("/", http.FileServer(http.Dir(arguments.web)))
	http.Handle("/render", websocket.Handler(renderServer))

	log.Println("waiting for connections...")
	if err := http.ListenAndServe(fmt.Sprintf(":%v", arguments.port), nil); err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}
開發者ID:andreas-jonsson,項目名稱:octatron,代碼行數:33,代碼來源:backend.go

示例2: main

func main() {
	flag.Parse()

	tempLog = temperatureLog{LogSize: 0, MaxLogSize: maxLogSize, Data: make([]temperatureLogEntry, 2)}
	tempLog.Data[0] = temperatureLogEntry{Label: "Boiler", Values: make([]temperatureLogValue, 0)}
	tempLog.Data[1] = temperatureLogEntry{Label: "Grouphead", Values: make([]temperatureLogValue, 0)}

	go h.broadcastLoop()

	if devMode {
		go devLoop()
	} else {
		go serialLoop()
	}

	http.HandleFunc("/buffer.json", bufferHandler)
	http.HandleFunc("/flush", flushHandler)
	http.Handle("/events", websocket.Handler(eventServer))
	http.Handle("/",
		http.FileServer(
			&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "views"}))

	portString := fmt.Sprintf(":%d", port)
	err := http.ListenAndServe(portString, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
開發者ID:gregose,項目名稱:PIDuino,代碼行數:28,代碼來源:PIDuino-ui.go

示例3: Start

func Start() {
	timeStart = time.Now()
	templates = template.Must(template.ParseFiles("www/index.html"))

	cfgCtrl := srv.Cfg().Get("server")
	sessionkey := cfgCtrl.Get("sessionkey").String()

	http.Handle("/rpc/", seshcookie.NewSessionHandler(&RpcHandler{}, sessionkey, nil))
	http.Handle("/upload", seshcookie.NewSessionHandler(&UploadHandler{}, sessionkey, nil))
	//http.HandleFunc("/vfile/", vfileHandler)
	http.Handle("/", seshcookie.NewSessionHandler(&WebHandler{}, sessionkey, nil))
	StartAuth()

	port := cfgCtrl.Get("port").String()
	if len(port) > 0 {
		srv.HttpListenAndServeAsync(":"+port, nil, "", "", "")
	}
	tlsport := cfgCtrl.Get("tlsport").String()
	if len(tlsport) > 0 && tlsport != "null" {
		srv.HttpListenAndServeAsync(":"+tlsport, nil, "tls_cert.pem", "tls_key.pem", "")
	}

	//srv.VersionDataDir = cfgCtrl.Get("data").String()
	//srv.DoRefreshVersions()
}
開發者ID:ChristophPech,項目名稱:servertest,代碼行數:25,代碼來源:web.go

示例4: main

func main() {
	http.Handle("/echo", websocket.Handler(echoHandler))
	http.Handle("/", http.FileServer(http.Dir("./")))
	if err := http.ListenAndServe(":8000", nil); err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
開發者ID:ikuwow,項目名稱:goSample,代碼行數:7,代碼來源:main.go

示例5: main

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)
}
開發者ID:Onills,項目名稱:CS130,代碼行數:7,代碼來源:main.go

示例6: main

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)
	}
}
開發者ID:alytvynov,項目名稱:goa,代碼行數:31,代碼來源:example.go

示例7: serve

func serve(port int) {
	jww.FEEDBACK.Println("Serving pages from " + helpers.AbsPathify(viper.GetString("PublishDir")))

	httpFs := &afero.HttpFs{SourceFs: hugofs.DestinationFS}
	fileserver := http.FileServer(httpFs.Dir(helpers.AbsPathify(viper.GetString("PublishDir"))))

	u, err := url.Parse(viper.GetString("BaseUrl"))
	if err != nil {
		jww.ERROR.Fatalf("Invalid BaseUrl: %s", err)
	}
	if u.Path == "" || u.Path == "/" {
		http.Handle("/", fileserver)
	} else {
		http.Handle(u.Path, http.StripPrefix(u.Path, fileserver))
	}

	u.Scheme = "http"
	jww.FEEDBACK.Printf("Web Server is available at %s\n", u.String())
	fmt.Println("Press Ctrl+C to stop")

	err = http.ListenAndServe(":"+strconv.Itoa(port), nil)
	if err != nil {
		jww.ERROR.Printf("Error: %s\n", err.Error())
		os.Exit(1)
	}
}
開發者ID:dunn,項目名稱:hugo,代碼行數:26,代碼來源:server.go

示例8: main

func main() {
	flag.Parse()
	go hub()
	var err error
	session, err = mgo.Mongo("localhost")

	if err != nil {
		panic("main > Mongo: " + err.Error())
	}
	defer session.Close()
	pfx := "/static/"
	h := http.StripPrefix(pfx, http.FileServer(http.Dir("../static/")))
	http.Handle(pfx, h) // It is absurd I had to work that hard to serve static files. Let's shove them on AWS or something and forget about it
	http.HandleFunc("/tickle", doTickle)
	http.HandleFunc("/keys", viewKeys)
	http.HandleFunc("/keys/add", addKey)
	http.HandleFunc("/keys/check", checkKey)
	http.HandleFunc("/links/send", sendLink)
	http.HandleFunc("/register", registerHandler)
	http.HandleFunc("/openid/callback", openID)
	http.HandleFunc("/openid/callback/chrome", openID)
	http.HandleFunc("/users/validate", validateUser)
	http.HandleFunc("/logout", doLogout)
	http.HandleFunc("/login", doLogin)
	http.HandleFunc("/links/", linksList)
	http.HandleFunc("/", rootHandler)
	http.Handle("/ws", websocket.Handler(wsHandler))
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
開發者ID:klinster,項目名稱:Bessie,代碼行數:31,代碼來源:twocloud.go

示例9: main

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)
}
開發者ID:ChrisKaufmann,項目名稱:feedinator-go,代碼行數:27,代碼來源:main.go

示例10: main

func main() {
	log.Trace("Starting")
	flag.Parse()

	if *blog_dir == "" {
		log.Error("Must specify a directory where blogs are stored")
		time.Sleep(1000)
		os.Exit(1)
	}

	blogs := blog.New()
	blogReader := reader.New(blogs, *blog_dir, log)
	v := view.New(blogs, log)
	router := router.New(v, log)

	err := blogReader.ReadBlogs()
	if err != nil {
		log.Error("Error creating blog reader: %s", err)
		time.Sleep(1000)
		os.Exit(1)
	}

	http.Handle("/", router)
	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
	err = http.ListenAndServe(":"+*protocol, nil)
	if err != nil {
		log.Error("Problem with http server: %s", err)
		time.Sleep(1000)
		os.Exit(1)
	}

	log.Trace("Stopping")
}
開發者ID:jasocox,項目名稱:goblog,代碼行數:33,代碼來源:main.go

示例11: main

func main() {
	addr := flag.String("addr", ":8080", "アプリケーションのアドレス")
	flag.Parse()

	gomniauth.SetSecurityKey("GoChat")
	gomniauth.WithProviders(
		google.New(googleClientID, googleSecret, "http://localhost:8080/auth/callback/google"),
	)

	r := newRoom()
	r.tracer = trace.New(os.Stdout)

	// http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {w.Write([]byte())})
	// http.Handle("/assets/", http.StripPrefix("/assets", http.FileServer(http.Dir("/assetsへのパス"))))
	// *templateHandler型(templateHandlerのポインタ型)にServeHTTPが実裝されている
	// のでtemplateHandlerのアドレスを渡してポインタである*templateHandler型を渡す
	http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	http.Handle("/login", &templateHandler{filename: "login.html"})
	http.HandleFunc("/auth/", loginHandler)
	http.Handle("/room", r)

	go r.run()

	log.Println("Webサーバを開始します。ポート: ", *addr)

	// start web server
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
開發者ID:bonegollira,項目名稱:gogo,代碼行數:30,代碼來源:main.go

示例12: main

func main() {
	var err error

	//Initialize mongodb connection, assuming mongo.go is present
	//If you are using another database setup, swap out this section
	mongodb_session, err = mgo.Dial(MONGODB_URL)
	if err != nil {
		panic(err)
	}
	mongodb_session.SetMode(mgo.Monotonic, true)
	mongodb_session.EnsureSafe(&mgo.Safe{1, "", 0, true, false})
	defer mongodb_session.Close()

	r := mux.NewRouter()

	r.HandleFunc("/", serveHome)
	r.HandleFunc("/callback", serveCallback).Methods("GET")
	r.HandleFunc("/register", serveRegister)
	r.HandleFunc("/login", serveLogin)
	r.Handle("/profile", &authHandler{serveProfile, false}).Methods("GET")
	http.Handle("/static/", http.FileServer(http.Dir("public")))
	http.Handle("/", r)

	if err := http.ListenAndServe(*httpAddr, nil); err != nil {
		log.Fatalf("Error listening, %v", err)
	}
}
開發者ID:jonzjia,項目名稱:go-server-bootstrap,代碼行數:27,代碼來源:server.go

示例13: serveHTTP

func serveHTTP() error {
	http.Handle("/", appHandler(handleStatic))
	http.Handle("/input", mjpegHandler(input))
	http.Handle("/output1", mjpegHandler(output1))
	http.Handle("/output2", mjpegHandler(output2))
	return http.ListenAndServe(*flagPort, nil)
}
開發者ID:barnex,項目名稱:ev3cam,代碼行數:7,代碼來源:server.go

示例14: main

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)
	}
}
開發者ID:paulgrock,項目名稱:ipl-irwin,代碼行數:27,代碼來源:irwin-server.go

示例15: init

func init() {
	r := httprouter.New()
	http.Handle("/", r)
	r.GET("/", cover)
	r.GET("/put", handlePut)
	r.GET("/get", handleGet)
	r.GET("/list", handleList)
	r.GET("/browse", browse)
	r.GET("/newStory", newStory)
	r.GET("/newScene", newScene)
	r.GET("/user/:name", profile)
	r.GET("/login", login)
	r.GET("/signup", signup)
	r.GET("/logout", logout)
	r.GET("/editProfile", editProfile)
	r.GET("/view/:story/:owner", viewStory)
	r.POST("/api/checkemail", checkEmail)
	r.POST("/api/checkusername", checkUserName)
	r.POST("/api/login", loginProcess)
	r.POST("/api/signup", createUser)
	r.POST("/api/editProfile", editProfileProcess)
	r.POST("/api/editPassword", editPassword)
	r.POST("/api/story", newStoryProcess)
	r.POST("/api/scene", newSceneProcess)
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))

	tpl = template.New("roottemplate")
	tpl = template.Must(tpl.ParseGlob("templates/*.html"))
}
開發者ID:sgkadle,項目名稱:AdvWebProg,代碼行數:29,代碼來源:main.go


注:本文中的net/http.Handle函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。