github.com/stackdocker/rkt@v0.10.1-0.20151109095037-1aa827478248/tests/testutils/httputils.go (about) 1 // Copyright 2015 The rkt Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package testutils 16 17 import ( 18 "fmt" 19 "io/ioutil" 20 "net" 21 "net/http" 22 "os" 23 "time" 24 25 "github.com/coreos/rkt/Godeps/_workspace/src/github.com/hydrogen18/stoppableListener" 26 "github.com/coreos/rkt/tests/testutils/logger" 27 ) 28 29 func HttpServe(addr string, timeout int) error { 30 hostname, err := os.Hostname() 31 if err != nil { 32 panic(err) 33 } 34 35 originalListener, err := net.Listen("tcp4", addr) 36 if err != nil { 37 panic(err) 38 } 39 sl, err := stoppableListener.New(originalListener) 40 if err != nil { 41 panic(err) 42 } 43 44 c := make(chan string) 45 go func() { 46 logger.Logf("%v: serving on %v\n", hostname, addr) 47 48 // Wait for either timeout or connect from client 49 select { 50 case <-time.After(time.Duration(timeout) * time.Second): 51 { 52 logger.Logf("%v: Serve timed out after %v seconds\n", hostname, timeout) 53 } 54 case client := (<-c): 55 { 56 logger.Logf("%v: Serve got a connection from %v\n", hostname, client) 57 } 58 } 59 sl.Stop() 60 }() 61 62 serveMux := http.NewServeMux() 63 serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 64 logger.Logf("%v: Serve got a connection from %v\n", hostname, r.RemoteAddr) 65 fmt.Fprintf(w, "%v", hostname) 66 c <- r.RemoteAddr 67 }) 68 err = http.Serve(sl, serveMux) 69 if err != nil && err.Error() == "Listener stopped" { 70 err = nil 71 } 72 return err 73 } 74 75 func HttpGet(addr string) (string, error) { 76 logger.Logf("Connecting to %v", addr) 77 res, err := http.Get(fmt.Sprintf("%v", addr)) 78 if err != nil { 79 return "", err 80 } 81 text, err := ioutil.ReadAll(res.Body) 82 res.Body.Close() 83 if err != nil { 84 return "", err 85 } 86 return string(text), nil 87 }