TryBugHunt
goScope errorEasy

Custom port setting is ignored and 8080 is always used

BugFind the bug and fix the code

What it should do

parsePort(value) reads a port number from a config value, using 8080 when the value is empty. parsePort("3000") returns 3000 and parsePort("") returns 8080.

What happens instead

parsePort("3000") returns 8080.

package main

import (
    "errors"
    "strconv"
)

func parsePort(value string) (int, error) {
    port := 8080
    if value != "" {
        port, err := strconv.Atoi(value)
        if err != nil {
            return 0, err
        }
        if port < 1 || port > 65535 {
            return 0, errors.New("port out of range")
        }
    }
    return port, nil
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the scope and closure bugs pattern

A variable redeclared with := so the outer one never changes, and loop variables captured late.

What you'll practise

An easy Go debugging exercise about scope and closure bugs: a variable redeclared with := so the outer one never changes, and loop variables captured late.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

Inside the if block, := declares a brand new port and err that live only in that block. The new port is parsed and validated correctly, then thrown away when the block ends, and the outer port is still 8080. Go allows this shadowing silently because the inner port is used. When you need the error variable but want to assign to an existing variable, declare err first and use plain =. go vet with the shadow analyzer, or a linter, can flag this pattern.

The pattern behind it: scope and closure bugs.

More scope and closure bugs to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/12aa9cfd-d5fe-4704-9f90-42c3764dc6c0" title="Debugging challenge: Custom port setting is ignored and 8080 is always used" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/12aa9cfd-d5fe-4704-9f90-42c3764dc6c0">TryBugHunt</a></p>