本文整理汇总了Golang中net/http.Server.ListenAndServe方法的典型用法代码示例。如果您正苦于以下问题:Golang Server.ListenAndServe方法的具体用法?Golang Server.ListenAndServe怎么用?Golang Server.ListenAndServe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Server
的用法示例。
在下文中一共展示了Server.ListenAndServe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: serveWebsite
// Serve the website. This function blocks.
func serveWebsite() {
port := 8080
// Sanity check to make sure we're in the right directory.
_, err := os.Stat("static/font.png")
if err != nil {
log.Fatal("You must be in the trs80 source directory (github.com/lkesteloot/trs80)")
}
// Create handlers.
handlers := http.NewServeMux()
handlers.Handle("/", webutil.GetHandler(http.HandlerFunc(homeHandler)))
handlers.Handle("/ws", websocket.Handler(wsHandler))
handlers.Handle("/static/", http.StripPrefix("/static/",
http.FileServer(http.Dir("static"))))
// Create server.
address := fmt.Sprintf(":%d", port)
server := http.Server{
Addr: address,
Handler: webutil.LoggingHandler(handlers),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: http.DefaultMaxHeaderBytes,
}
// Start serving.
log.Printf("Serving website on %s", address)
err = server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
示例2: main
func main() {
Data[1] = "a"
Data[2] = "b"
Data[3] = "c"
Data[4] = "d"
Data[5] = "e"
Data[6] = "f"
Data[7] = "g"
Data[8] = "h"
Data[9] = "i"
Data[10] = "j"
for _, each := range Instances {
Cache[g_p(each)] = each
}
for k, _ := range Data {
Cache[g_p(strconv.Itoa(k))] = strconv.Itoa(k)
}
for k, _ := range Cache {
S_keys = append(S_keys, k)
}
sort.Strings(S_keys)
mux := httprouter.New()
mux.PUT("/keys/:key/:value", put_h)
mux.GET("/keys/:key", h_get)
server := http.Server{
Addr: "0.0.0.0:8187",
Handler: mux,
}
server.ListenAndServe()
}
示例3: ExampleSessionMux
func ExampleSessionMux() {
sb := NewSrvSessionBuilder("", "/", "example", 60*60*1000, 10000)
mux := NewSessionMux("/example", sb)
mux.HFilterFunc("^.*$", func(hs *HTTPSession) HResult {
log.D("filt 001")
return HRES_CONTINUE
})
//http://localhost:8080/example/ok
mux.HFunc("^/ok(\\?.*)?$", func(hs *HTTPSession) HResult {
hs.MsgRes("OK")
return HRES_RETURN
})
//http://localhost:8080/example/data
mux.HFunc("^/data(\\?.*)?$", func(hs *HTTPSession) HResult {
var tid int64
var name string
err := hs.ValidRVal(`
tid,R|I,R:0
name,R|S,L:0`, //valid the argument
&tid, &name)
if err != nil {
return hs.MsgResE(1, err.Error())
}
return hs.MsgRes(fmt.Sprintf("%v:%v", tid, name))
})
mux.HFunc("^/mdata(\\?.*)?$", func(hs *HTTPSession) HResult {
hs.W.Write([]byte("some data\n"))
return HRES_RETURN
})
s := http.Server{Addr: ":8080", Handler: mux}
err := s.ListenAndServe()
if err != nil {
fmt.Println(err)
}
}
示例4: main
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
Handler: nil,
}
server.ListenAndServe()
}
示例5: main
func main() {
Values[1] = "z"
Values[2] = "y"
Values[3] = "x"
Values[4] = "q"
Values[5] = "w"
Values[6] = "v"
Values[7] = "u"
Values[8] = "t"
Values[9] = "s"
Values[10] = "r"
for _, each := range ListOfServers {
HashingMapping[calculateHashValue(each)] = each
}
for k, _ := range Values {
HashingMapping[calculateHashValue(strconv.Itoa(k))] = strconv.Itoa(k)
}
for k, _ := range HashingMapping {
SortedHashingMappingKeys = append(SortedHashingMappingKeys, k)
}
sort.Strings(SortedHashingMappingKeys)
mux := httprouter.New()
mux.PUT("/keys/:key/:value", putDataTo)
mux.GET("/keys/:key", getRequest)
server := http.Server{
Addr: "0.0.0.0:8000",
Handler: mux,
}
server.ListenAndServe()
}
示例6: StartServer
func StartServer(server *http.Server) {
log.Println("Starting server")
err := server.ListenAndServe()
if err != nil {
log.Fatalln("Error: %v", err)
}
}
示例7: Run
// Run provides starting of server
func (hs *HttpServer) Run() {
server := http.Server{
Addr: hs.Addr,
}
go server.ListenAndServe()
}
示例8: main
func main() {
sourceAddress := ":3000"
ports := []string{
":3333",
":3334",
}
hostRing := ring.New(len(ports))
for _, port := range ports {
url, _ := url.Parse("http://127.0.0.1" + port)
hostRing.Value = url
hostRing = hostRing.Next()
}
mutex := sync.Mutex{}
director := func(request *http.Request) {
mutex.Lock()
defer mutex.Unlock()
request.URL.Scheme = "http"
request.URL.Host = hostRing.Value.(*url.URL).Host
hostRing = hostRing.Next()
fmt.Println(hostRing)
}
proxy := &httputil.ReverseProxy{Director: director}
server := http.Server{
Addr: sourceAddress,
Handler: proxy,
}
server.ListenAndServe()
}
示例9: main
func main() {
initService()
var port = flag.String("port", "8000", "please specify the port to start server on")
flag.Parse()
logger.Println("Port to start on: " + *port)
server := http.Server{
Addr: ":" + *port,
Handler: &myHandler{},
}
mux = make(map[string]func(http.ResponseWriter, *http.Request))
mux["/"] = homeHandler
mux["/healthmetrics"] = healthMetricsHandler
mux["/addhealthmetrics"] = addHealthMetricsHandler
mux["/addhealthmetricsform"] = addHealthMetricsFormHandler
mux["/newuser"] = addUserHandler
mux["/signupform"] = signupFormHandler
mux["/login"] = loginHandler
mux["/loginform"] = loginformHandler
mux["/logout"] = logoutHandler
mux["/static"] = staticHandler
server.ListenAndServe()
}
示例10: Serve
func (h *HTTPServer) Serve(launchdSocket string) error {
proxy := &httputil.ReverseProxy{
Director: h.director,
Transport: h.transport,
FlushInterval: 1 * time.Second,
}
serv := http.Server{
Addr: h.Address,
Handler: proxy,
}
if launchdSocket == "" {
return serv.ListenAndServe()
}
listeners, err := launch.SocketListeners(launchdSocket)
if err != nil {
return err
}
var t tomb.Tomb
for _, l := range listeners {
t.Go(func() error {
return serv.Serve(l)
})
}
return t.Wait()
}
示例11: main
func main() {
var httpServer http.Server
var httpsServer http.Server
http2.VerboseLogs = true
http2.ConfigureServer(&httpsServer, nil)
http.HandleFunc("/auth", authHandler)
http.HandleFunc("/", handler)
http.HandleFunc("/js", jsHandler)
var wg sync.WaitGroup
wg.Add(2)
go func() {
log.Println("start http listening :18888")
httpServer.Addr = ":18888"
log.Println(httpServer.ListenAndServe())
wg.Done()
}()
go func() {
log.Println("start https listening :18889")
httpsServer.Addr = ":18889"
log.Println(httpsServer.ListenAndServeTLS("server.crt", "server.key"))
wg.Done()
}()
wg.Wait()
}
示例12: main
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/post/", handleRequest)
server.ListenAndServe()
}
示例13: main
func main() {
var err error
var f *os.File
f, err = os.Open("/var/www/index.html")
if err != nil {
log.Fatal(err)
}
index_bytes, err = ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
err = f.Close()
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", http_index)
var srv *http.Server
srv = &http.Server{
ReadTimeout: 30 * time.Second,
Handler: http.DefaultServeMux,
}
go func() {
var err error
err = srv.ListenAndServe()
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}()
log.Println("Started")
select {}
}
示例14: main
func main() {
Data[1] = "a"
Data[2] = "b"
Data[3] = "c"
Data[4] = "d"
Data[5] = "e"
Data[6] = "f"
Data[7] = "g"
Data[8] = "h"
Data[9] = "i"
Data[10] = "j"
for _, each := range ServerArr {
HashMap[getHash(each)] = each
}
for k, _ := range Data {
HashMap[getHash(strconv.Itoa(k))] = strconv.Itoa(k)
}
for k, _ := range HashMap {
SortedHashMapKeys = append(SortedHashMapKeys, k)
}
sort.Strings(SortedHashMapKeys)
mux := httprouter.New()
mux.PUT("/keys/:key/:value", handlePutRequests)
mux.GET("/keys/:key", handleGetRequests)
server := http.Server{
Addr: "0.0.0.0:8000",
Handler: mux,
}
server.ListenAndServe()
}
示例15: StartServer
// StartServer Starts the OAuth2 token exchange server. Blocks until the server is killed.
func StartServer() {
clientKeysFile, err := os.Open(clientKeysPath)
if err != nil {
log.Fatal(err)
}
clientKeysDecoder := json.NewDecoder(clientKeysFile)
var clientKeys ClientKeys
if err = clientKeysDecoder.Decode(&clientKeys); err != nil {
log.Fatal(err)
}
log.Println("Client ID:", clientKeys.ClientID)
log.Println("Client Secret:", clientKeys.ClientSecret)
userTokensFile, err := os.OpenFile(userTokensPath, os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
defer userTokensFile.Close()
log.Println("Listening")
http.HandleFunc("/auth/exchange", makeTokenExchangeHandler(clientKeys, userTokensFile))
server := http.Server{
Addr: ":8080",
Handler: nil,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(server.ListenAndServe())
}