ProgramGuru

Working with Query Parameters

Start with Working with Query Parameters

In this lesson, explore working with query parameters through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of working with query parameters.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Query parameters follow a ? in a URL, for example ?page=2&sort=name. Use r.URL.Query().Get("page") to read a value.

Query strings are untrusted input. Validate numbers and acceptable values; distinguish a missing parameter from a valid default.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for query paramsQuery strings need explicit validation.URL ?page=2Step 1Query().GetStep 2Validate integerStep 3Return pageStep 4Query strings need explicit validation.
Query strings need explicit validation.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strconv"
)

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		page, err := strconv.Atoi(r.URL.Query().Get("page"))
		if err != nil || page < 1 {
			http.Error(w, "invalid page", http.StatusBadRequest)
			return
		}
		fmt.Fprint(w, "Page ", page)
	})
	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, httptest.NewRequest("GET", "/?page=2", nil))
	fmt.Print(rec.Body.String())
}

Output

Page 2

Trace what the program does

Query().Get returns "2"; Atoi parses it as 2. The handler writes Page 2. Bad values are rejected before use.

Avoid common mistakes

  • A query parameter is optional unless your handler requires it.
  • Never concatenate unchecked query values directly into SQL statements.

Try it yourself

Add a limit query parameter and reject values outside 1..100.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which API reads query string values?
Choose one answer. You can try again.

Answer and explanation

r.URL.Query().Get

Correct. Query().

What you should remember

You have practiced Working with Query Parameters in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Handling Request Bodies →