mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-24 10:01:38 +00:00
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?
This commit is contained in:
parent
f90cdc44bb
commit
f2e3d99476
@ -329,17 +329,31 @@ func learnConcurrency() {
|
|||||||
|
|
||||||
// A single function from package http starts a web server.
|
// A single function from package http starts a web server.
|
||||||
func learnWebProgramming() {
|
func learnWebProgramming() {
|
||||||
|
|
||||||
// First parameter of ListenAndServe is TCP address to listen to.
|
// First parameter of ListenAndServe is TCP address to listen to.
|
||||||
// Second parameter is an interface, specifically http.Handler.
|
// Second parameter is an interface, specifically http.Handler.
|
||||||
|
go func() {
|
||||||
err := http.ListenAndServe(":8080", pair{})
|
err := http.ListenAndServe(":8080", pair{})
|
||||||
fmt.Println(err) // don't ignore errors
|
fmt.Println(err) // don't ignore errors
|
||||||
|
}()
|
||||||
|
|
||||||
|
requestServer();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Make pair an http.Handler by implementing its only method, ServeHTTP.
|
// Make pair an http.Handler by implementing its only method, ServeHTTP.
|
||||||
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
// Serve data with a method of http.ResponseWriter.
|
// Serve data with a method of http.ResponseWriter.
|
||||||
w.Write([]byte("You learned Go in Y minutes!"))
|
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
|
## Further Reading
|
||||||
|
Loading…
Reference in New Issue
Block a user