تمرين إعادة البناء
Concurrent Status Checker
أعد كتابة برنامج Go يفحص روابط محلية بالتوازي.
go
~22 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"sort"
"sync"
)
type Result struct {
Path string
Code int
}
func checkPaths(handler http.Handler, paths []string) []Result {
results := make([]Result, 0, len(paths))
resultCh := make(chan Result)
var wg sync.WaitGroup
for _, path := range paths {
wg.Add(1)
go func(path string) {
defer wg.Done()
request := httptest.NewRequest(http.MethodGet, path, nil)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
resultCh <- Result{Path: path, Code: recorder.Result().StatusCode}
}(path)
}
go func() {
wg.Wait()
close(resultCh)
}()
for result := range resultCh {
results = append(results, result)
}
sort.Slice(results, func(i, j int) bool {
return results[i].Path < results[j].Path
})
return results
}
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/", "/health":
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
})
for _, result := range checkPaths(handler, []string{"/", "/missing", "/health"}) {
fmt.Printf("%-8s %d\n", result.Path, result.Code)
}
}اكتب هنا