Posted in: Uncategorized

Get a URL Parameter from a client Request

Often it’s important to read off the parameters sent through from the request. If it’s a GET request these will lie within the url itself and can be read using the request’s URL property. It’s important to note that when getting the parameters in this way it will always return an array (or slice?).

Our example below will act a little like an echo server, we listen for any requests and log the result of key if it’s present.

Example when calling localhost:8080/?key=hello%20golangcode.com:

package main
import (
    “fmt”
    “log”
    “net/http”
)
func main() {
    http.HandleFunc(“/”, handler)
    http.ListenAndServe(“:8080”, nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
    keys, ok := r.URL.Query()[“key”]
    if !ok || len(keys[0]) < 1 {
        log.Println(“Url Param ‘key’ is missing”)
        return
    }
    // Query()[“key”] will return an array of items,
    // we only want the single item.
    key := keys[0:]
    fmt.Fprintf(w, “URL.PATH = %q \n”, r.URL.Path)
    fmt.Fprint(w, key)
    log.Println(“Url Param ‘key’ is: “, key)
}


Leave a Reply

Your email address will not be published. Required fields are marked *