From f2e3d99476c0b549e468e3090d0938322e8142d4 Mon Sep 17 00:00:00 2001 From: Vincent Voyer Date: Wed, 2 Jul 2014 14:55:33 +0200 Subject: feat(webserver request): add a http.Get example 1. script now exits 2. we initiate a request to the started server to prove the serverHTTP works what do you think? --- go.html.markdown | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'go.html.markdown') diff --git a/go.html.markdown b/go.html.markdown index a9a7de72..61d7db84 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -329,17 +329,31 @@ func learnConcurrency() { // A single function from package http starts a web server. func learnWebProgramming() { + // First parameter of ListenAndServe is TCP address to listen to. // Second parameter is an interface, specifically http.Handler. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // don't ignore errors + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors + }() + + requestServer(); } + // Make pair an http.Handler by implementing its only method, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Serve data with a method of http.ResponseWriter. w.Write([]byte("You learned Go in Y minutes!")) } + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWebserver said: `%s`", string(body)) +} ``` ## Further Reading -- cgit v1.2.3