当前位置: 首页>>代码示例>>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;未经允许,请勿转载。