go
56 lines · 7 steps
Parsing search query params in a Go handler
An HTTP handler that safely reads, validates, and defaults query parameters before running a search.
Explained by
highlit
1package handlers
2
3import (
4 "encoding/json"
5 "net/http"
6 "strconv"
7 "strings"
8)
9
10type searchParams struct {
11 Query string
12 Tags []string
13 Page int
14 PerPage int
15 SortDesc bool
16}
17
18func SearchHandler(w http.ResponseWriter, r *http.Request) {
19 if err := r.ParseForm(); err != nil {
20 http.Error(w, "invalid form encoding", http.StatusBadRequest)
21 return
22 }
23
24 p := searchParams{
25 Query: strings.TrimSpace(r.FormValue("q")),
26 Page: 1,
27 PerPage: 25,
28 SortDesc: r.FormValue("order") == "desc",
29 }
30
31 for _, tag := range r.Form["tag"] {
32 if tag = strings.TrimSpace(tag); tag != "" {
33 p.Tags = append(p.Tags, tag)
34 }
35 }
36
37 if page, err := strconv.Atoi(r.FormValue("page")); err == nil && page > 0 {
38 p.Page = page
39 }
40 if per, err := strconv.Atoi(r.FormValue("per_page")); err == nil && per > 0 && per <= 100 {
41 p.PerPage = per
42 }
43
44 results, total, err := searchArticles(r.Context(), p)
45 if err != nil {
46 http.Error(w, "search failed", http.StatusInternalServerError)
47 return
48 }
49
50 w.Header().Set("Content-Type", "application/json")
51 json.NewEncoder(w).Encode(map[string]any{
52 "results": results,
53 "total": total,
54 "page": p.Page,
55 })
56}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Start from sensible defaults and only overwrite them when incoming input parses and passes bounds checks.
- 2Validating page and per-page limits at the edge protects downstream queries from abusive or malformed input.
- 3Guarding each failure with an early return keeps the happy path flat and readable.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-search-query-params-in-a-go-handler-explained-go-ee7a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.