How to Create http NewServeMux and run with go routine?

huangapple go评论66阅读模式
英文:

How to Create http NewServeMux and run with go routine?

问题

我有一个关于http.NewServeMux的问题,我尝试使用go routine运行,但它不起作用。

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func run() (s *http.Server) {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		rw.WriteHeader(http.StatusOK)
		fmt.Fprint(rw, "under construction")
	})

	s = &http.Server{
		Addr:           ":8080",
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	return
}

func main() {
	s := run()
	quit := make(chan os.Signal)

	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		cancel()
	}()
	if err := s.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown")
	}
	log.Println("Server exiting")
}

然后使用以下命令运行:

go run main.go

并访问http://localhost:8080/,总是得到404页面未找到。

你可以如何解决这个问题?

英文:

I have an issue about http.NewServeMux, I've tried to run with go routine but it's doesn't work.

package main
import (
&quot;context&quot;
&quot;fmt&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;os&quot;
&quot;os/signal&quot;
&quot;syscall&quot;
&quot;time&quot;
)
func run() (s *http.Server) {
mux := http.NewServeMux()
mux.HandleFunc(&quot;/&quot;, func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusOK)
fmt.Fprint(rw, &quot;under construction&quot;)
})
s = &amp;http.Server{
Addr:           &quot;:8080&quot;,
ReadTimeout:    10 * time.Second,
WriteTimeout:   10 * time.Second,
MaxHeaderBytes: 1 &lt;&lt; 20,
}
go func() {
if err := s.ListenAndServe(); err != nil &amp;&amp; err != http.ErrServerClosed {
log.Fatalf(&quot;listen: %s\n&quot;, err)
}
}()
return
}
func main() {
s := run()
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
&lt;-quit
log.Println(&quot;Shutting down server...&quot;)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err := s.Shutdown(ctx); err != nil {
log.Fatal(&quot;Server forced to shutdown&quot;)
}
log.Println(&quot;Server exiting&quot;)
}

then run with
> go run main.go

And access to http://localhost:8080/ that's always to get.

>404 page not found

How I can solve this issue?

答案1

得分: 0

这是因为你设置了 mux,但从未对其进行任何操作:

    // 在添加默认处理程序后,mux 没有被引用
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
        rw.WriteHeader(http.StatusOK)
        fmt.Fprint(rw, "正在建设中")
    })

将处理程序更改为使用 mux 变量而不是 http.DefaultServeMux,一切都会按预期工作:

	s = &http.Server{
		Handler:        mux, // 这是重要的一行
		Addr:           ":8080",
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
英文:

This is because you're setting up mux but never do anything with it:

    // mux is never referenced after you add the default handler
    mux := http.NewServeMux()
    mux.HandleFunc(&quot;/&quot;, func(rw http.ResponseWriter, r *http.Request) {
        rw.WriteHeader(http.StatusOK)
        fmt.Fprint(rw, &quot;under construction&quot;)
    })

Change your handler to use your mux var instead of http.DefaultServeMux and everything works as expected:

	s = &amp;http.Server{
		Handler:        mux, // This is the important line
		Addr:           &quot;:8080&quot;,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 &lt;&lt; 20,
	}

huangapple
  • 本文由 发表于 2021年8月7日 08:26:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68688559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定