本文整理汇总了Golang中net/http.ListenAndServe函数的典型用法代码示例。如果您正苦于以下问题:Golang ListenAndServe函数的具体用法?Golang ListenAndServe怎么用?Golang ListenAndServe使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ListenAndServe函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
flag.Parse()
if flag.NArg() != 1 {
log.Fatal("filename not specified")
}
filename := flag.Args()[0]
h := &handler{
filename: filename,
c: make(chan bool),
}
// Watch file(s) for changes and trigger refresh
go h.watcher(h.filename)
http.HandleFunc("/ws/echo", h.reloadHandler)
http.Handle("/", h)
go http.ListenAndServe(":3000", nil)
err := http.ListenAndServe(":3000", nil)
if err != nil {
panic("Error: " + err.Error())
}
fmt.Println("Done")
}
示例2: 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)
}
}
示例3: ListenAndServe
// ListenAndServe method serve plots via http on port. HTML docs should be under the webRoot directory.
// This routine won't return so kick off any other processes as a goroutine.
func (l *Logger) ListenAndServe(port, webRoot string) {
var err error
if l.step != nil {
http.HandleFunc("/step", func(w http.ResponseWriter, r *http.Request) {
sendJSON(w, r, <-l.step)
})
http.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
l.start <- empty{}
})
}
http.HandleFunc("/stats/", l.statsHandler(len("/stats/")))
http.HandleFunc("/plot/List", func(w http.ResponseWriter, r *http.Request) {
sendJSON(w, r, l.options)
})
http.HandleFunc("/plot/Plot", func(w http.ResponseWriter, r *http.Request) {
sendJSON(w, r, l.plots)
})
http.HandleFunc("/plot/SVGPlot", func(w http.ResponseWriter, r *http.Request) {
send(w, r, l.svgplot, "image/svg+xml")
})
http.HandleFunc("/plot/Hist", l.histogramPlotHandler())
http.HandleFunc("/plot/", l.statsPlotHandler(len("/plot/")))
http.HandleFunc("/graph", l.graphHandler())
http.Handle("/", http.FileServer(http.Dir(webRoot)))
log.Println("starting web server on", port)
if Debug {
err = http.ListenAndServe(port, logRequests(http.DefaultServeMux))
} else {
err = http.ListenAndServe(port, nil)
}
log.Fatal(err)
}
示例4: main
func main() {
router := mux.NewRouter()
ctx := context.Background()
svc := yell.YellingService{}
yellHandler := httptransport.NewServer(
ctx,
yell.MakeYellEndpoint(svc),
yell.DecodeYellRequest,
yell.EncodeResponse,
)
composeHandler := httptransport.NewServer(
ctx,
compose.MakeComposeEndpoint(svc),
compose.DecodeComposeRequest,
compose.EncodeResponse,
)
router.HandleFunc("/", RootHandler)
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(*staticPath))))
http.Handle("/yell", yellHandler)
http.Handle("/compose", composeHandler)
go http.ListenAndServe(":8080", nil)
go log.Fatal(http.ListenAndServe(":8081", router))
}
示例5: main
func main() {
rand.Seed(time.Now().UTC().UnixNano())
if len(os.Args) > 1 && os.Args[1] == "web" {
handler := func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
for k, v := range r.Form {
if k == "height" {
height, _ = strconv.Atoi(strings.Join(v, ""))
} else if k == "width" {
width, _ = strconv.Atoi(strings.Join(v, ""))
} else if k == "color" {
color = v[0]
}
}
w.Header().Set("Content-Type", "image/svg+xml")
drawSVG(w, r)
}
http.HandleFunc("/", handler)
//!-http
log.Fatal(http.ListenAndServe("localhost:8000", nil))
return
}
http.HandleFunc("/draw", drawSVG)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
示例6: main
func main() {
if len(os.Args) > 1 {
switch os.Args[1] {
case "setup":
defer lazyblog.DefaultStore.Close()
lazyblog.Setup()
case "start":
defer lazyblog.DefaultStore.Close()
numUsers, err := lazyblog.NumUsers()
if err != nil {
panic(err)
}
if numUsers < 1 {
log.Fatalln("Please run setup before running start")
return
}
if os.Getenv("LAZYBLOG_ENV") == "dev" {
log.Fatalln(http.ListenAndServe(":3000", lazyblog.Router))
}
log.Fatalln(http.ListenAndServe(":80", lazyblog.Router))
default:
fmt.Println(usage)
}
} else {
fmt.Println(usage)
}
}
示例7: main
func main() {
dataDirectory := flag.String("d", defaultDataDirectory, "Directory where dictionary files are located")
serviceListenPort := flag.Int("p", defaultServiceListenPort, "Service Listen Port")
adminListenPort := flag.Int("a", defaultAdminListenPort, "Admin Listen Port")
allowedOrigin := flag.String("c", handlers.AllowedOrigin, "CORS Allowed Origin")
flag.Parse()
log.Printf("Using data directory %s", *dataDirectory)
handlers.DataDirectory = *dataDirectory
handlers.LoadDictionaries()
r := mux.NewRouter()
r.HandleFunc("/twocents", handlers.MetaVersionsHandler).Methods("GET")
r.HandleFunc("/twocents/{version:v1}", handlers.MetaDictionariesHandler).Methods("GET")
r.HandleFunc("/twocents/{version:v1}/{dictionary}/{query}", handlers.TwoCentsHandlerV1).Methods("GET")
r.HandleFunc("/twocents/{version:v1}/{dictionary}/{query}/{limit:[0-9]+}", handlers.TwoCentsHandlerV1).Methods("GET")
r.HandleFunc("/twocents/{version:v1}/{dictionary}/{query}/{limit:[0-9]+}/{filter}", handlers.TwoCentsHandlerV1).Methods("GET")
http.Handle("/", r)
log.Printf("Service listening on port %d", *serviceListenPort)
go func() {
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *serviceListenPort), nil))
}()
log.Printf("Admin listening on port %d", *adminListenPort)
if *allowedOrigin != "" {
log.Printf("Setting CORS Origin to %s", *allowedOrigin)
handlers.AllowedOrigin = *allowedOrigin
}
//TODO: Find a better way to pass a different router to the admin server
http.ListenAndServe(fmt.Sprintf(":%d", *adminListenPort), &adminHandler{})
}
示例8: main
func main() {
f := flag.String("config", "$HOME/.config/mallory.json", "config file")
flag.Parse()
L.Printf("Starting...\n")
c, err := m.NewConfig(*f)
if err != nil {
L.Fatalln(err)
}
L.Printf("Connecting remote SSH server: %s\n", c.File.RemoteServer)
smart, err := m.NewServer(m.SmartSrv, c)
if err != nil {
L.Fatalln(err)
}
normal, err := m.NewServer(m.NormalSrv, c)
if err != nil {
L.Fatalln(err)
}
go func() {
L.Printf("Local normal HTTP proxy: %s\n", c.File.LocalNormalServer)
L.Fatalln(http.ListenAndServe(c.File.LocalNormalServer, normal))
}()
L.Printf("Local smart HTTP proxy: %s\n", c.File.LocalSmartServer)
L.Fatalln(http.ListenAndServe(c.File.LocalSmartServer, smart))
}
示例9: main
func main() {
logger := log.NewLogger()
cfg := config.Default()
flag.StringVar(&cfg.WSAddress, "ws", cfg.WSAddress, "Websocket address")
flag.StringVar(&cfg.RESTAddress, "rest", cfg.RESTAddress, "REST address")
flag.StringVar(&cfg.Origin, "o", cfg.Origin, "Origin URL")
file := flag.String("config", "", "Config file")
flag.Parse()
if *file != "" {
err := config.FromFile(*file, &cfg)
if err != nil {
logger.Err.Fatal(err)
}
flag.Parse()
}
broker := pubsub.NewBroker()
go func() {
wsRouter := mux.NewRouter()
wsRouter.Handle("/{id}", handlers.WSHandler{Broker: broker, Config: cfg, Logger: logger})
logger.Out.Println("Listening websockets on", cfg.WSAddress)
logger.Err.Fatal(http.ListenAndServe(cfg.WSAddress, wsRouter))
}()
go func() {
restRouter := mux.NewRouter()
restRouter.Handle("/topic", handlers.List{Broker: broker, Logger: logger}).Methods("GET")
restRouter.Handle("/topic", handlers.Add{Broker: broker, Logger: logger}).Methods("POST")
restRouter.Handle("/topic/{id}", handlers.Pub{Broker: broker, Logger: logger}).Methods("POST")
restRouter.Handle("/topic/{id}", handlers.Del{Broker: broker, Logger: logger}).Methods("DELETE")
restRouter.Handle("/ping", handlers.Ping{Logger: logger}).Methods("GET")
logger.Out.Println("Listening REST on", cfg.RESTAddress)
logger.Err.Fatal(http.ListenAndServe(cfg.RESTAddress, restRouter))
}()
wait := make(chan struct{})
<-wait
}
示例10: main
func main() {
location2 = 0
location3 = 0
location1 = 0
mutliplexer := httprouter.New()
mutliplexer.GET("/keys", PingRedisPorts)
mutliplexer.GET("/keys/:key_id", GetOneKey)
mutliplexer.PUT("/keys/:key_id/:value", AddKeyValues)
mutliplexer.GET("/all", AllRedisKeyValues)
mutliplexer.GET("/mapping", GetMapping)
go http.ListenAndServe(":3000", mutliplexer)
go http.ListenAndServe(":3001", mutliplexer)
go http.ListenAndServe(":3002", mutliplexer)
select {}
}
示例11: main
func main() {
port := flag.Int("port", 6969, "port to serve websockets on")
cport := flag.Int("cport", 6868, "port to listen for control messages on")
nCpu := flag.Int("ncpu", runtime.NumCPU(), "number of cpus to use, defaults to number of processors available")
mgrVerbose := flag.Bool("verbose-merry-go-round", false, "Verbose output from merry-go-round carousels")
flag.Parse()
runtime.GOMAXPROCS(*nCpu)
mgr.VERBOSE = *mgrVerbose
ss := socketserver.NewSocketServer()
go func() {
bindAddr := fmt.Sprintf(":%d", *port)
fmt.Printf("SocketServer going up at: %s\n", bindAddr)
log.Fatal(http.ListenAndServe(bindAddr, ss))
}()
sc := control.NewSocketController(ss)
bindAddr := fmt.Sprintf(":%d", *cport)
fmt.Printf("SocketController going up at: %s\n", bindAddr)
log.Fatal(http.ListenAndServe(bindAddr, sc))
}
示例12: main
func main() {
flag.Parse()
if *uberClientId == "" || *uberClientSecret == "" || *httpsUrl == "" || *httpUrl == "" || *googleMapsApiKey == "" {
flag.PrintDefaults()
return
}
uberApiClient = &UberApiClient{
url: *uberApiHost,
clientSecret: *uberClientSecret,
clientId: *uberClientId,
}
mondoApiClient = &MondoApiClient{url: *mondoApiUrl}
router.HandleFunc("/", indexGet).Methods("GET").Name(Index)
router.HandleFunc("/login", loginPost).Methods("POST").Name(Login)
router.HandleFunc("/logout", logoutPost).Methods("POST").Name(Logout)
router.HandleFunc("/uber/setauthcode", uberSetAuthCodeGet).Methods("GET").Name(SetAuthCode)
router.HandleFunc("/mondo/webhook/{sessionId}", mondoWebhookPost).Methods("POST").Name(MondoWebhook)
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./")))
go func() {
log.Printf("Listening on %s\n", *httpAddr)
log.Fatal(http.ListenAndServe(*httpAddr, middleware(router)))
}()
log.Printf("Listening on %s\n", *httpsAddr)
if strings.Contains(*httpsAddr, "443") {
log.Fatal(http.ListenAndServeTLS(*httpsAddr, *certFile, *keyFile, middleware(router)))
} else {
log.Fatal(http.ListenAndServe(*httpsAddr, middleware(router)))
}
}
示例13: main
func main() {
flag.Parse()
r := mux.NewRouter()
operatorPost := make(chan []byte)
clientPost := make(chan []byte)
clientGet := make(chan []byte)
gameToOperator := make(chan []byte)
r.Path("/frontend").Methods("GET").HandlerFunc(handleClientGet(clientGet))
r.Path("/frontend").Methods("POST").HandlerFunc(handleClientPost(clientPost))
r.Path("/move").Methods("POST").HandlerFunc(handleOperatorPost(operatorPost, gameToOperator))
go func() {
var previousGame []byte
for {
sendGameToClient := clientGet
if previousGame == nil {
sendGameToClient = nil
}
select {
case x := <-clientPost:
gameToOperator <- x
previousGame = nil
case x := <-operatorPost:
previousGame = x
case sendGameToClient <- previousGame:
}
}
}()
go func() {
http.ListenAndServe(":"+*port, r)
}()
http.ListenAndServe(":1337", r)
}
示例14: main
func main() {
// Setup the global variables and settings
err := models.Setup()
if err != nil {
fmt.Println(err)
}
wg := &sync.WaitGroup{}
wg.Add(1)
// Start the web servers
go func() {
defer wg.Done()
if config.Conf.AdminConf.UseTLS { // use TLS for Admin web server if available
Logger.Printf("Starting admin server at https://%s\n", config.Conf.AdminConf.ListenURL)
Logger.Fatal(http.ListenAndServeTLS(config.Conf.AdminConf.ListenURL, config.Conf.AdminConf.CertPath, config.Conf.AdminConf.KeyPath,
handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
} else {
Logger.Printf("Starting admin server at http://%s\n", config.Conf.AdminConf.ListenURL)
Logger.Fatal(http.ListenAndServe(config.Conf.AdminConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
}
}()
wg.Add(1)
go func() {
defer wg.Done()
if config.Conf.PhishConf.UseTLS { // use TLS for Phish web server if available
Logger.Printf("Starting phishing server at https://%s\n", config.Conf.PhishConf.ListenURL)
Logger.Fatal(http.ListenAndServeTLS(config.Conf.PhishConf.ListenURL, config.Conf.PhishConf.CertPath, config.Conf.PhishConf.KeyPath,
handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
} else {
Logger.Printf("Starting phishing server at http://%s\n", config.Conf.PhishConf.ListenURL)
Logger.Fatal(http.ListenAndServe(config.Conf.PhishConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
}
}()
wg.Wait()
}
示例15: main
func main() {
db, err := bolt.Open("proxy.db", 0600, nil)
if err != nil {
log.Fatal("Fatal: %s\n", err.Error())
}
defer db.Close()
adminServer := proxyAdminServer{db}
adminMux := bone.New()
adminMux.Get("/proxy", http.HandlerFunc(adminServer.GetProxies))
adminMux.Delete("/proxy/:id", http.HandlerFunc(adminServer.DeleteProxyIteraction))
adminMux.Post("/proxy", http.HandlerFunc(adminServer.NewProxyIteraction))
proxyServer := proxyServer{&http.Client{}, db}
mux := bone.New()
mux.Handle("/*", http.HandlerFunc(proxyServer.ProxyHandler))
go func(port string) {
log.Println("Starting admin server")
log.Fatal(http.ListenAndServe(port, adminMux))
}(":9080")
log.Println("Starting test proxy")
log.Fatal(http.ListenAndServe(":9090", mux))
}