Run and build Task Code Check the version go versionStart a module go mod init krlab/helloRun the program go run . a bBuild a binary go build -o hello .Cross-build for Windows GOOS=windows GOARCH=arm64 go build -o hello.exe .List unformatted files gofmt -l .Build a small static release CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o portcheck .Show modules inside a binary go version -m helloRead the documentation of a function go doc strings.CutList the names of a package go doc -short strings
Types and collections Task Code Declare with a type var host string = "127.0.0.1"Declare and infer port := 8080Append to a slice ports = append(ports, 8080)Copy a slice copy(c, a)Test a map key name, ok := names[8080]Remove a map key delete(names, 80)Sort a slice by a rule sort.Slice(list, func(i, j int) bool { return list[i].Port > list[j].Port })Count characters len([]rune(word))Print a struct with field names fmt.Printf("%+v\n", f)
Functions, errors and packages Task Code Split at the first colon host, port, found := strings.Cut(t, ":")Turn text into a number n, err := strconv.Atoi(s)Wrap an error fmt.Errorf("parse port %q: %w", s, err)Test for a known error errors.Is(err, portspec.ErrRange)Close a file on exit defer f.Close()Give a type a method func (f Finding) String() string { ... }Name what a method must have type Checker interface { Check(host string) string }
var ErrRange = errors. New ( "port out of range" )
func Parse ( s string ) ( int , error ) {
n, err := strconv. Atoi ( s)
if err != nil {
return 0 , fmt. Errorf ( "parse port %q: %w" , s, err)
}
return n, nil
} Files, JSON and flags Task Code Read lines sc := bufio.NewScanner(f), sc.Scan()Check a scan error sc.Err()Write JSON json.MarshalIndent(list, "", " ")Read JSON json.Unmarshal([]byte(text), &f)Take an address, and write through it p := &x, *p = 6Write a private file os.WriteFile(out, append(data, '\n'), 0o600)Define a flag in := flag.String("in", "hosts.txt", "input file")Parse flags flag.Parse()Exit with a code os.Exit(2)
HTTP client and server Task Code Make a client with a timeout &http.Client{Timeout: 3 * time.Second}Build a request with a context http.NewRequestWithContext(ctx, http.MethodGet, url, nil)Limit the body to 1 MB io.LimitReader(resp.Body, 1<<20)Add a deadline ctx, cancel := context.WithTimeout(context.Background(), time.Second)Route one method mux.HandleFunc("GET /health", handler)Bind a test server to loopback Addr: "127.0.0.1:8201"Split a URL u, err := url.Parse(raw), u.Hostname()Do not follow a redirect CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
Concurrency Task Code Start a goroutine go f()Wait for all goroutines wg.Add(1), defer wg.Done(), wg.Wait()Protect a shared counter mu.Lock(), count++, mu.Unlock()Find a data race go run -race .Tell workers no more jobs come close(jobCh)
Tests and fuzzing Task Code Run all tests go test ./...Skip the test cache go test -count=1 ./...Check for suspect code go vet ./...Test with the race detector go test -race ./...Run a fuzz test go test -fuzz=FuzzParse -fuzztime=5s ./portspecShow each test and its result go test -race -v ./scanOpen a free test port net.Listen("tcp", "127.0.0.1:0")Start a test server srv := httptest.NewServer(handler), defer srv.Close(), srv.URLGet a folder for a test file dir := t.TempDir()
tests := [] struct {
in string
want int
}{
{ "80" , 80 },
{ "443" , 443 },
}
for _, tc := range tests {
t. Run ( tc. in, func ( t * testing. T) {
got, err := Parse ( tc. in)
if err != nil || got != tc. want {
t. Errorf ( "Parse(%q) = %d, %v; want %d" , tc. in, got, err, tc. want)
}
})
} Task Code Define a number, a time and a switch flag.Int(...), flag.Duration(...), flag.Bool(...)Stop on Ctrl+C ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)Open a connection that obeys a context conn, err := d.DialContext(ctx, "tcp", addr)Join a host and a port net.JoinHostPort(host, strconv.Itoa(p))Run the port checker ./portcheck -from 1 -to 1024 -json
Exit codes Code Meaning 0 Success. 1 A failure while running (a file or a network error). 2 Wrong use of the command line, or a refused target. 3 The tool ran, and found a difference or a down endpoint.
Safety habits Never ignore an error with _ in a tool that makes security decisions. Set a timeout on every client. Never use plain http.Get. Never use InsecureSkipVerify. Add your own certificate to a pool. Keep secrets out of source code and error text. Scan only systems you own or may test. Default to 127.0.0.1, and refuse other hosts in the code. Do not follow a redirect to another host in a tool that must stay on one machine. Make report files private with 0o600.