github.com/xmidt-org/webpa-common@v1.11.9/xhttp/gate/lever.go (about)

     1  package gate
     2  
     3  import (
     4  	"net/http"
     5  	"strconv"
     6  
     7  	"github.com/go-kit/kit/log/level"
     8  	"github.com/xmidt-org/webpa-common/logging"
     9  	"github.com/xmidt-org/webpa-common/xhttp"
    10  )
    11  
    12  // Lever is an http.Handler which controls the state of a gate.
    13  type Lever struct {
    14  	// Gate is the gate this lever controls
    15  	Gate Interface
    16  
    17  	// Parameter is the HTTP parameter, which must be a bool, used to set the state of the gate
    18  	Parameter string
    19  }
    20  
    21  func (l *Lever) ServeHTTP(response http.ResponseWriter, request *http.Request) {
    22  	logger := logging.GetLogger(request.Context())
    23  
    24  	if err := request.ParseForm(); err != nil {
    25  		logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "bad form request", logging.ErrorKey(), err)
    26  		xhttp.WriteError(response, http.StatusBadRequest, err)
    27  		return
    28  	}
    29  
    30  	v := request.FormValue(l.Parameter)
    31  	if len(v) == 0 {
    32  		logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "no parameter found", "parameter", l.Parameter)
    33  		xhttp.WriteErrorf(response, http.StatusBadRequest, "missing %s parameter", l.Parameter)
    34  		return
    35  	}
    36  
    37  	f, err := strconv.ParseBool(v)
    38  	if err != nil {
    39  		logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "parameter is not a bool", "parameter", l.Parameter, logging.ErrorKey(), err)
    40  		xhttp.WriteErrorf(response, http.StatusBadRequest, "the %s parameter must be a bool", l.Parameter)
    41  		return
    42  	}
    43  
    44  	var changed bool
    45  	if f {
    46  		changed = l.Gate.Raise()
    47  	} else {
    48  		changed = l.Gate.Lower()
    49  	}
    50  
    51  	logger.Log(level.Key(), level.InfoValue(), logging.MessageKey(), "gate update", "open", f, "changed", changed)
    52  
    53  	if changed {
    54  		response.WriteHeader(http.StatusCreated)
    55  	} else {
    56  		response.WriteHeader(http.StatusOK)
    57  	}
    58  }