github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/http/example_test.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package http_test 6 7 import ( 8 "fmt" 9 "io/ioutil" 10 "log" 11 "net/http" 12 ) 13 14 func ExampleHijacker() { 15 http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) { 16 hj, ok := w.(http.Hijacker) 17 if !ok { 18 http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError) 19 return 20 } 21 conn, bufrw, err := hj.Hijack() 22 if err != nil { 23 http.Error(w, err.Error(), http.StatusInternalServerError) 24 return 25 } 26 // Don't forget to close the connection: 27 defer conn.Close() 28 bufrw.WriteString("Now we're speaking raw TCP. Say hi: ") 29 bufrw.Flush() 30 s, err := bufrw.ReadString('\n') 31 if err != nil { 32 log.Printf("error reading string: %v", err) 33 return 34 } 35 fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s) 36 bufrw.Flush() 37 }) 38 } 39 40 func ExampleGet() { 41 res, err := http.Get("http://www.google.com/robots.txt") 42 if err != nil { 43 log.Fatal(err) 44 } 45 robots, err := ioutil.ReadAll(res.Body) 46 res.Body.Close() 47 if err != nil { 48 log.Fatal(err) 49 } 50 fmt.Printf("%s", robots) 51 } 52 53 func ExampleFileServer() { 54 // Simple static webserver: 55 log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) 56 } 57 58 func ExampleFileServer_stripPrefix() { 59 // To serve a directory on disk (/tmp) under an alternate URL 60 // path (/tmpfiles/), use StripPrefix to modify the request 61 // URL's path before the FileServer sees it: 62 http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) 63 } 64 65 func ExampleStripPrefix() { 66 // To serve a directory on disk (/tmp) under an alternate URL 67 // path (/tmpfiles/), use StripPrefix to modify the request 68 // URL's path before the FileServer sees it: 69 http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) 70 } 71 72 type apiHandler struct{} 73 74 func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} 75 76 func ExampleServeMux_Handle() { 77 mux := http.NewServeMux() 78 mux.Handle("/api/", apiHandler{}) 79 mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 80 // The "/" pattern matches everything, so we need to check 81 // that we're at the root here. 82 if req.URL.Path != "/" { 83 http.NotFound(w, req) 84 return 85 } 86 fmt.Fprintf(w, "Welcome to the home page!") 87 }) 88 }