Dealing with zero-length non-empty form values in Go

This is an example Go program which demonstrates how to distinguish between non-existent form values and empty form values, for example form values which come from submitting when nothing is in the text box.

It is not possible to access these simply using the FormValue method of http.Request, so this looks at the value of Form in the http.Request and checks for the case of a defined but empty value using the second return value from a map.

package main

import (
        "fmt"
        "log"
        "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
        value := r.FormValue("thing")
        if len(value) > 0 {
                fmt.Fprintf(w, "Got a value %s\n", value)
                return
        }
        if _, ok := r.Form["thing"]; ok {
                fmt.Fprintf(w, "Got the thing key but it was empty.\n")
                return
        }
        fmt.Fprintf(w, `<html><body><form><input name="thing"></form></body></html>`)
}

func main() {
        http.HandleFunc("/", handler)
        log.Fatal(http.ListenAndServe(":8080", nil))
}

(download)

The output of http://localhost:8080/?thing=mikan looks like

Got a value mikan

The output of http://localhost:8080/?thing= looks like

Got the thing key but it was empty.

Copyright © Ben Bullock 2009-2022. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer