github.com/abayer/test-infra@v0.0.5/mungegithub/sharedmux/sharedmux.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package sharedmux
    18  
    19  import (
    20  	"fmt"
    21  	"net/http"
    22  	"strings"
    23  	"sync"
    24  )
    25  
    26  var (
    27  	// Admin is the schelling point for those who want to provide admin
    28  	// actions and those who want to install the admin portal in some port.
    29  	Admin = NewAdminMux()
    30  )
    31  
    32  // ConcurrentMux is safe to call HandleFunc on even after it's started serving
    33  // requests.
    34  type ConcurrentMux struct {
    35  	mux      *http.ServeMux
    36  	pathList []string
    37  	lock     sync.RWMutex
    38  }
    39  
    40  // NewConcurrentMux constructs a mux.
    41  func NewConcurrentMux(mux *http.ServeMux) *ConcurrentMux {
    42  	return &ConcurrentMux{
    43  		mux: mux,
    44  	}
    45  }
    46  
    47  func NewAdminMux() *ConcurrentMux {
    48  	c := NewConcurrentMux(http.NewServeMux())
    49  	c.Handle("/", http.HandlerFunc(c.listHTTP))
    50  	return c
    51  }
    52  
    53  // Handle installs the given handler.
    54  func (c *ConcurrentMux) Handle(pattern string, handler http.Handler) {
    55  	c.lock.Lock()
    56  	defer c.lock.Unlock()
    57  	c.mux.Handle(pattern, handler)
    58  	c.pathList = append(c.pathList, pattern)
    59  }
    60  
    61  // HandleFunc installs the given handler function.
    62  func (c *ConcurrentMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
    63  	c.Handle(pattern, http.HandlerFunc(handler))
    64  }
    65  
    66  // ServeHTTP serves according to the added handlers.
    67  func (c *ConcurrentMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    68  	c.lock.RLock()
    69  	defer c.lock.RUnlock()
    70  	c.mux.ServeHTTP(w, r)
    71  }
    72  
    73  // listHTTP lists handlers that have been added.
    74  func (c *ConcurrentMux) listHTTP(w http.ResponseWriter, r *http.Request) {
    75  	c.lock.RLock()
    76  	defer c.lock.RUnlock()
    77  	fmt.Fprintf(w, "Possible paths:\n%v\n", strings.Join(c.pathList, "\n"))
    78  }