1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
請(qǐng)您親自查看,下面的程序?qū)y(cè)試這兩種情況。
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"
它的工作原理是手動(dòng)創(chuàng)建兩個(gè)偵聽(tīng)不同本地地址的 HTTP 服務(wù)器。每個(gè)服務(wù)器都有不同的多路復(fù)用器設(shè)置。然后它獲取具有多個(gè)不同URL的兩個(gè)服務(wù)器。在繼續(xù)之前,將重試多次抓取,直到?jīng)]有發(fā)生錯(cuò)誤來(lái)解釋未同步的服務(wù)器啟動(dòng)。輸出是在 TabWriter 的幫助下格式化的。
- 1 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報(bào)