istio
56 строк · 1.7 Кб
1// Copyright Istio 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
15package testserver
16
17import (
18"net"
19"net/http"
20"net/http/httptest"
21)
22
23// CreateAndStartServer starts a server and returns the response passed.
24func CreateAndStartServer(response string) *httptest.Server {
25return createHTTPServer(createDefaultFuncMap(response))
26}
27
28func createHTTPServer(handlers map[string]func(rw http.ResponseWriter, _ *http.Request)) *httptest.Server {
29mux := http.NewServeMux()
30for k, v := range handlers {
31mux.HandleFunc(k, http.HandlerFunc(v))
32}
33
34// Start a local HTTP server
35server := httptest.NewUnstartedServer(mux)
36
37l, err := net.Listen("tcp", ":0")
38if err != nil {
39panic("Could not create listener for test: " + err.Error())
40}
41server.Listener = l
42server.Start()
43return server
44}
45
46func createDefaultFuncMap(statsToReturn string) map[string]func(rw http.ResponseWriter, _ *http.Request) {
47return map[string]func(rw http.ResponseWriter, _ *http.Request){
48"/stats": func(rw http.ResponseWriter, _ *http.Request) {
49// Send response to be tested
50_, err := rw.Write([]byte(statsToReturn))
51if err != nil {
52panic("Could not write response: " + err.Error())
53}
54},
55}
56}
57