istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pilot/cmd/pilot-agent/status/testserver/server.go (about)

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