diff options
Diffstat (limited to 'go.html.markdown')
-rw-r--r-- | go.html.markdown | 43 |
1 files changed, 30 insertions, 13 deletions
diff --git a/go.html.markdown b/go.html.markdown index 88e2c8da..0ecc6120 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -202,25 +202,28 @@ func learnFlowControl() { goto love love: + learnFunctionFactory() // func returning func is fun(3)(3) learnDefer() // A quick detour to an important keyword. learnInterfaces() // Good stuff coming up! } +func learnFunctionFactory() { + // Next two are equivalent, with second being more practical + fmt.Println(sentenceFactory("summer")("A beautiful", "day!")) + + d := sentenceFactory("summer") + fmt.Println(d("A beautiful", "day!")) + fmt.Println(d("A lazy", "afternoon!")) +} + // Decorators are common in other languages. Same can be done in Go // with function literals that accept arguments. -func learnFunctionFactory(mystring string) func(before, after string) string { - return func(before, after string) string { - return fmt.Sprintf("%s %s %s", before, mystring, after) // new string - } +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + } } -// Next two are equivalent, with second being more practical -fmt.Println(learnFunctionFactory("summer")("A beautiful", "day!")) - -d := learnFunctionFactory("summer") -fmt.Println(d("A beautiful", "day!")) -fmt.Println(d("A lazy", "afternoon!")) - func learnDefer() (ok bool) { // Deferred statements are executed just before the function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") @@ -339,17 +342,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 |