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 關注
- 97 瀏覽
添加回答
舉報