1 回答
TA贡献1820条经验 获得超10个赞
请您亲自查看,下面的程序将测试这两种情况。
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"text/tabwriter"
"time"
)
func main() {
srv1 := &http.Server{
Addr: "localhost:9090",
}
go func() {
mux := http.NewServeMux()
fileServer := http.FileServer(http.Dir("./html"))
mux.Handle("/", fileServer)
srv1.Handler = mux
srv1.ListenAndServe()
}()
srv2 := &http.Server{
Addr: "localhost:9091",
}
go func() {
mux := http.NewServeMux()
fileServer := http.FileServer(http.Dir("./html"))
mux.Handle("/html/", http.StripPrefix("/html/", fileServer))
srv2.Handler = mux
srv2.ListenAndServe()
}()
srvs := []*http.Server{srv1, srv2}
urls := []string{
"http://%v/index.css",
"http://%v/html/index.css",
}
// u := fmt.Sprintf("http://%v/html/index.css", srv.Addr)
w := new(tabwriter.Writer)
w.Init(os.Stdout, 8, 8, 0, '\t', 0)
defer fmt.Println()
defer w.Flush()
fmt.Fprintf(w, "\n %s\t%s\t", "URL", "Response")
fmt.Fprintf(w, "\n %s\t%s\t", "----", "----")
for _, srv := range srvs {
for _, f := range urls {
<-time.After(time.Millisecond * 200)
u := fmt.Sprintf(f, srv.Addr)
res, err := http.Get(u)
if err != nil {
continue
}
var out bytes.Buffer
io.Copy(&out, res.Body)
res.Body.Close()
fmt.Fprintf(w, "\n %s\t%s\t", u, fmt.Sprintf("%q", out.String()))
}
}
}
它输出
$ go run .
URL Response
---- ----
http://localhost:9090/index.css "OK\n"
http://localhost:9090/html/index.css "404 page not found\n"
http://localhost:9091/index.css "404 page not found\n"
http://localhost:9091/html/index.css "OK\n"
它的工作原理是手动创建两个侦听不同本地地址的 HTTP 服务器。每个服务器都有不同的多路复用器设置。然后它获取具有多个不同URL的两个服务器。在继续之前,将重试多次抓取,直到没有发生错误来解释未同步的服务器启动。输出是在 TabWriter 的帮助下格式化的。
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报