Kontrola odkazů v čistém Go: GET /check?url=... stáhne cíl a odpoví jeho stavovým kódem a dobou odezvy. Všechno pochází ze standardní knihovny a server čte PORT z prostředí s lokálním výchozím portem, takže go run . funguje beze změny i u vás.
Go se na takovou službu hodí: zkompilovaná binárka má pár megabajtů, v klidu spotřebuje jednotky megabajtů paměti a startuje v milisekundách, což je přesně to, co chcete od služby, která mezi požadavky spí.
package main // A tiny link checker: GET /check?url=https://example.com answers with the // status code and how long the request took. The standard library carries // the whole service; the binary built from it is a few megabytes and starts // in milliseconds. import ( "encoding/json" "fmt" "log" "net/http" "os" "time" ) func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "GET /check?url=https://example.com") }) http.HandleFunc("/check", func(w http.ResponseWriter, r *http.Request) { target := r.URL.Query().Get("url") if target == "" { http.Error(w, "missing ?url=", http.StatusUnprocessableEntity) return } client := &http.Client{Timeout: 10 * time.Second} start := time.Now() resp, err := client.Get(target) elapsed := time.Since(start) w.Header().Set("content-type", "application/json; charset=utf-8") if err != nil { w.WriteHeader(http.StatusBadGateway) json.NewEncoder(w).Encode(map[string]any{"url": target, "error": err.Error()}) return } defer resp.Body.Close() json.NewEncoder(w).Encode(map[string]any{ "url": target, "status": resp.StatusCode, "ms": elapsed.Milliseconds(), }) }) fmt.Println("Serving on localhost:" + port) log.Fatal(http.ListenAndServe(":"+port, nil)) }
module go-link-checker go 1.26
Go beyond what seems possible.