golang http get request with parameters code example
Example 1: golang http get query parameters
package main
import (
"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
}
key := keys[0]
log.Println("Url Param 'key' is: " + string(key))
}
Example 2: golang get request data
package main
func fetchResponse(url string) string{
resp, _ := http.Get(url)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return string(body)
}
func main() {
resp := fetchResponse("http://someurl.com")
fmt.Println(resp)
}