You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@trafficcontrol.apache.org by GitBox <gi...@apache.org> on 2018/06/12 22:05:29 UTC

[GitHub] mitchell852 closed pull request #2365: Add TO Go api helpers

mitchell852 closed pull request #2365: Add TO Go api helpers
URL: https://github.com/apache/incubator-trafficcontrol/pull/2365
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/traffic_ops/traffic_ops_golang/api/api.go b/traffic_ops/traffic_ops_golang/api/api.go
new file mode 100644
index 000000000..59b38da7f
--- /dev/null
+++ b/traffic_ops/traffic_ops_golang/api/api.go
@@ -0,0 +1,304 @@
+package api
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"context"
+	"database/sql"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"net/http"
+	"strconv"
+	"strings"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/config"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
+
+	"github.com/jmoiron/sqlx"
+)
+
+const DBContextKey = "db"
+const ConfigContextKey = "context"
+
+// WriteResp takes any object, serializes it as JSON, and writes that to w. Any errors are logged and written to w via tc.GetHandleErrorsFunc.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func WriteResp(w http.ResponseWriter, r *http.Request, v interface{}) {
+	resp := struct {
+		Response interface{} `json:"response"`
+	}{v}
+	WriteRespRaw(w, r, resp)
+}
+
+// WriteRespRaw acts like WriteResp, but doesn't wrap the object in a `{"response":` object. This should be used to respond with endpoints which don't wrap their response in a "response" object.
+func WriteRespRaw(w http.ResponseWriter, r *http.Request, v interface{}) {
+	bts, err := json.Marshal(v)
+	if err != nil {
+		log.Errorf("marshalling JSON (raw) for %T: %v", v, err)
+		tc.GetHandleErrorsFunc(w, r)(http.StatusInternalServerError, errors.New(http.StatusText(http.StatusInternalServerError)))
+		return
+	}
+	w.Header().Set("Content-Type", "application/json")
+	w.Write(bts)
+}
+
+// WriteRespVals is like WriteResp, but also takes a map of root-level values to write. The API most commonly needs these for meta-parameters, like size, limit, and orderby.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func WriteRespVals(w http.ResponseWriter, r *http.Request, v interface{}, vals map[string]interface{}) {
+	vals["response"] = v
+	respBts, err := json.Marshal(vals)
+	if err != nil {
+		log.Errorf("marshalling JSON for %T: %v", v, err)
+		tc.GetHandleErrorsFunc(w, r)(http.StatusInternalServerError, errors.New(http.StatusText(http.StatusInternalServerError)))
+		return
+	}
+	w.Header().Set("Content-Type", "application/json")
+	w.Write(respBts)
+}
+
+// HandleErr handles an API error, writing the given statusCode and userErr to the user, and logging the sysErr. If userErr is nil, the text of the HTTP statusCode is written.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func HandleErr(w http.ResponseWriter, r *http.Request, statusCode int, userErr error, sysErr error) {
+	if sysErr != nil {
+		log.Errorln(r.RemoteAddr + " " + sysErr.Error())
+	}
+	if userErr == nil {
+		userErr = errors.New(http.StatusText(statusCode))
+	}
+	respBts, err := json.Marshal(tc.CreateErrorAlerts(userErr))
+	if err != nil {
+		log.Errorln("marshalling error: " + err.Error())
+		*r = *r.WithContext(context.WithValue(r.Context(), tc.StatusKey, http.StatusInternalServerError))
+		w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
+		return
+	}
+	*r = *r.WithContext(context.WithValue(r.Context(), tc.StatusKey, statusCode))
+	w.Header().Set(tc.ContentType, tc.ApplicationJson)
+	w.Write(respBts)
+}
+
+// RespWriter is a helper to allow a one-line response, for endpoints with a function that returns the object that needs to be written and an error.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func RespWriter(w http.ResponseWriter, r *http.Request) func(v interface{}, err error) {
+	return func(v interface{}, err error) {
+		if err != nil {
+			HandleErr(w, r, http.StatusInternalServerError, nil, err)
+			return
+		}
+		WriteResp(w, r, v)
+	}
+}
+
+// RespWriterVals is like RespWriter, but also takes a map of root-level values to write. The API most commonly needs these for meta-parameters, like size, limit, and orderby.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func RespWriterVals(w http.ResponseWriter, r *http.Request, vals map[string]interface{}) func(v interface{}, err error) {
+	return func(v interface{}, err error) {
+		if err != nil {
+			HandleErr(w, r, http.StatusInternalServerError, nil, err)
+			return
+		}
+		WriteRespVals(w, r, v, vals)
+	}
+}
+
+// WriteRespAlert creates an alert, serializes it as JSON, and writes that to w. Any errors are logged and written to w via tc.GetHandleErrorsFunc.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func WriteRespAlert(w http.ResponseWriter, r *http.Request, level tc.AlertLevel, msg string) {
+	resp := struct{ tc.Alerts }{tc.CreateAlerts(level, msg)}
+	respBts, err := json.Marshal(resp)
+	if err != nil {
+		HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("marshalling JSON: "+err.Error()))
+		return
+	}
+	w.Header().Set(tc.ContentType, tc.ApplicationJson)
+	w.Write(respBts)
+}
+
+// IntParams parses integer parameters, and returns map of the given params, or an error if any integer param is not an integer. The intParams may be nil if no integer parameters are required. Note this does not check existence; if an integer paramter is required, it should be included in the requiredParams given to NewInfo.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func IntParams(params map[string]string, intParamNames []string) (map[string]int, error) {
+	intParams := map[string]int{}
+	for _, intParam := range intParamNames {
+		valStr, ok := params[intParam]
+		if !ok {
+			continue
+		}
+		valInt, err := strconv.Atoi(valStr)
+		if err != nil {
+			return nil, errors.New("parameter '" + intParam + "'" + " not an integer")
+		}
+		intParams[intParam] = valInt
+	}
+	return intParams, nil
+}
+
+// ParamsHaveRequired checks that params have all the required parameters, and returns nil on success, or an error providing information on which params are missing.
+func ParamsHaveRequired(params map[string]string, required []string) error {
+	missing := []string{}
+	for _, requiredParam := range required {
+		if _, ok := params[requiredParam]; !ok {
+			missing = append(missing, requiredParam)
+		}
+	}
+	if len(missing) > 0 {
+		return errors.New("missing required parameters: " + strings.Join(missing, ", "))
+	}
+	return nil
+}
+
+// StripParamJSON removes ".json" trailing any parameter value, and returns the modified params.
+// This allows the API handlers to transparently accept /id.json routes, as allowed by the 1.x API.
+func StripParamJSON(params map[string]string) map[string]string {
+	for name, val := range params {
+		if strings.HasSuffix(val, ".json") {
+			params[name] = val[:len(val)-len(".json")]
+		}
+	}
+	return params
+}
+
+// AllParams takes the request (in which the router has inserted context for path parameters), and an array of parameters required to be integers, and returns the map of combined parameters, and the map of int parameters; or a user or system error and the HTTP error code. The intParams may be nil if no integer parameters are required.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func AllParams(req *http.Request, required []string, ints []string) (map[string]string, map[string]int, error, error, int) {
+	params, err := GetCombinedParams(req)
+	if err != nil {
+		return nil, nil, errors.New("getting combined URI parameters: " + err.Error()), nil, http.StatusBadRequest
+	}
+	params = StripParamJSON(params)
+	if err := ParamsHaveRequired(params, required); err != nil {
+		return nil, nil, errors.New("required parameters missing: " + err.Error()), nil, http.StatusBadRequest
+	}
+	intParams, err := IntParams(params, ints)
+	if err != nil {
+		return nil, nil, nil, errors.New("getting integer parameters: " + err.Error()), http.StatusInternalServerError
+	}
+	return params, intParams, nil, nil, 0
+}
+
+type ParseValidator interface {
+	Validate(tx *sql.Tx) error
+}
+
+// Decode decodes a JSON object from r into the given v, validating and sanitizing the input. This helper should be used in API endpoints, rather than the json package, to safely decode and validate PUT and POST requests.
+// TODO change to take data loaded from db, to remove sql from tc package.
+func Parse(r io.Reader, tx *sql.Tx, v ParseValidator) error {
+	if err := json.NewDecoder(r).Decode(&v); err != nil {
+		return errors.New("decoding: " + err.Error())
+	}
+	if err := v.Validate(tx); err != nil {
+		return errors.New("validating: " + err.Error())
+	}
+	return nil
+}
+
+type APIInfo struct {
+	Params    map[string]string
+	IntParams map[string]int
+	User      *auth.CurrentUser
+	Tx        *sqlx.Tx
+	CommitTx  *bool
+	Config    *config.Config
+}
+
+// NewInfo get and returns the context info needed by handlers. It also returns any user error, any system error, and the status code which should be returned to the client if an error occurred.
+// Close() must be called to free resources, and should be called in a defer immediately after NewInfo(), to commit or rollback the transaction.
+//
+// Example:
+//  func handler(w http.ResponseWriter, r *http.Request) {
+//    inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)
+//    if userErr != nil || sysErr != nil {
+//      api.HandleErr(w, r, errCode, userErr, sysErr)
+//      return
+//    }
+//    defer inf.Close()
+//
+//    err := databaseOperation(inf.Tx)
+//    if err == nil {
+//      *inf.CommitTx = true
+//    }
+//
+func NewInfo(r *http.Request, requiredParams []string, intParamNames []string) (*APIInfo, error, error, int) {
+	db, err := getDB(r.Context())
+	if err != nil {
+		return nil, errors.New("getting db: " + err.Error()), nil, http.StatusInternalServerError
+	}
+	cfg, err := getConfig(r.Context())
+	if err != nil {
+		return nil, errors.New("getting config: " + err.Error()), nil, http.StatusInternalServerError
+	}
+	user, err := auth.GetCurrentUser(r.Context())
+	if err != nil {
+		return nil, errors.New("getting user: " + err.Error()), nil, http.StatusInternalServerError
+	}
+	params, intParams, userErr, sysErr, errCode := AllParams(r, requiredParams, intParamNames)
+	if userErr != nil || sysErr != nil {
+		return nil, userErr, sysErr, errCode
+	}
+	tx, err := db.Beginx() // must be last, MUST not return an error if this suceeds, without closing the tx
+	if err != nil {
+		return nil, userErr, errors.New("could not begin transaction: " + err.Error()), http.StatusInternalServerError
+	}
+	falsePtr := false
+	return &APIInfo{
+		Config:    cfg,
+		Params:    params,
+		IntParams: intParams,
+		User:      user,
+		Tx:        tx,
+		CommitTx:  &falsePtr,
+	}, nil, nil, http.StatusOK
+}
+
+// Close implements the io.Closer interface. It should be called in a defer immediately after NewInfo().
+//
+// Close will commit or rollback the transaction, depending whether *info.CommitTx is true.
+func (inf *APIInfo) Close() {
+	dbhelpers.FinishTxX(inf.Tx, inf.CommitTx)
+}
+
+func getDB(ctx context.Context) (*sqlx.DB, error) {
+	val := ctx.Value(DBContextKey)
+	if val != nil {
+		switch v := val.(type) {
+		case *sqlx.DB:
+			return v, nil
+		default:
+			return nil, fmt.Errorf("DB found with bad type: %T", v)
+		}
+	}
+	return nil, errors.New("No db found in Context")
+}
+
+func getConfig(ctx context.Context) (*config.Config, error) {
+	val := ctx.Value(ConfigContextKey)
+	if val != nil {
+		switch v := val.(type) {
+		case *config.Config:
+			return v, nil
+		default:
+			return nil, fmt.Errorf("Config found with bad type: %T", v)
+		}
+	}
+	return nil, errors.New("No config found in Context")
+}
diff --git a/traffic_ops/traffic_ops_golang/api/shared_handlers.go b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
index 061397a06..356c0309a 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_handlers.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
@@ -416,123 +416,3 @@ func CreateHandler(typeRef Creator, db *sqlx.DB) http.HandlerFunc {
 		fmt.Fprintf(w, "%s", respBts)
 	}
 }
-
-// WriteResp takes any object, serializes it as JSON, and writes that to w. Any errors are logged and written to w via tc.GetHandleErrorsFunc.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func WriteResp(w http.ResponseWriter, r *http.Request, v interface{}) {
-	resp := struct {
-		Response interface{} `json:"response"`
-	}{v}
-	respBts, err := json.Marshal(resp)
-	if err != nil {
-		log.Errorf("marshalling JSON for %T: %v", v, err)
-		tc.GetHandleErrorsFunc(w, r)(http.StatusInternalServerError, errors.New(http.StatusText(http.StatusInternalServerError)))
-		return
-	}
-	w.Header().Set("Content-Type", "application/json")
-	w.Write(respBts)
-}
-
-// WriteRespVals is like WriteResp, but also takes a map of root-level values to write. The API most commonly needs these for meta-parameters, like size, limit, and orderby.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func WriteRespVals(w http.ResponseWriter, r *http.Request, v interface{}, vals map[string]interface{}) {
-	vals["response"] = v
-	respBts, err := json.Marshal(vals)
-	if err != nil {
-		log.Errorf("marshalling JSON for %T: %v", v, err)
-		tc.GetHandleErrorsFunc(w, r)(http.StatusInternalServerError, errors.New(http.StatusText(http.StatusInternalServerError)))
-		return
-	}
-	w.Header().Set("Content-Type", "application/json")
-	w.Write(respBts)
-}
-
-// HandleErr handles an API error, writing the given statusCode and userErr to the user, and logging the sysErr. If userErr is nil, the text of the HTTP statusCode is written.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func HandleErr(w http.ResponseWriter, r *http.Request, statusCode int, userErr error, sysErr error) {
-	if sysErr != nil {
-		log.Errorln(r.RemoteAddr + " " + sysErr.Error())
-	}
-	if userErr == nil {
-		userErr = errors.New(http.StatusText(statusCode))
-	}
-	respBts, err := json.Marshal(tc.CreateErrorAlerts(userErr))
-	if err != nil {
-		log.Errorln("marshalling error: " + err.Error())
-		*r = *r.WithContext(context.WithValue(r.Context(), tc.StatusKey, http.StatusInternalServerError))
-		w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
-		return
-	}
-	*r = *r.WithContext(context.WithValue(r.Context(), tc.StatusKey, statusCode))
-	w.Header().Set(tc.ContentType, tc.ApplicationJson)
-	w.Write(respBts)
-}
-
-// RespWriter is a helper to allow a one-line response, for endpoints with a function that returns the object that needs to be written and an error.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func RespWriter(w http.ResponseWriter, r *http.Request) func(v interface{}, err error) {
-	return func(v interface{}, err error) {
-		if err != nil {
-			HandleErr(w, r, http.StatusInternalServerError, nil, err)
-			return
-		}
-		WriteResp(w, r, v)
-	}
-}
-
-// RespWriterVals is like RespWriter, but also takes a map of root-level values to write. The API most commonly needs these for meta-parameters, like size, limit, and orderby.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func RespWriterVals(w http.ResponseWriter, r *http.Request, vals map[string]interface{}) func(v interface{}, err error) {
-	return func(v interface{}, err error) {
-		if err != nil {
-			HandleErr(w, r, http.StatusInternalServerError, nil, err)
-			return
-		}
-		WriteRespVals(w, r, v, vals)
-	}
-}
-
-// WriteRespAlert creates an alert, serializes it as JSON, and writes that to w. Any errors are logged and written to w via tc.GetHandleErrorsFunc.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func WriteRespAlert(w http.ResponseWriter, r *http.Request, level tc.AlertLevel, msg string) {
-	resp := struct{ tc.Alerts }{tc.CreateAlerts(level, msg)}
-	respBts, err := json.Marshal(resp)
-	if err != nil {
-		HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("marshalling JSON: "+err.Error()))
-		return
-	}
-	w.Header().Set(tc.ContentType, tc.ApplicationJson)
-	w.Write(respBts)
-}
-
-// IntParams parses integer parameters, and returns map of the given params, or an error. This guarantees if error is nil, all requested parameters successfully parsed and exist in the returned map, hence if error is nil there's no need to check for existence. The intParams may be nil if no integer parameters are required.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func IntParams(params map[string]string, intParamNames []string) (map[string]int, error) {
-	intParams := map[string]int{}
-	for _, intParam := range intParamNames {
-		realParam, ok := params[intParam]
-		if !ok {
-			return nil, errors.New("missing required integer parameter '" + intParam + "'")
-		}
-		intVal, err := strconv.Atoi(realParam)
-		if err != nil {
-			return nil, errors.New("required parameter '" + intParam + "'" + " not an integer")
-		}
-		intParams[intParam] = intVal
-	}
-	return intParams, nil
-}
-
-// AllParams takes the request (in which the router has inserted context for path parameters), and an array of parameters required to be integers, and returns the map of combined parameters, and the map of int parameters; or a user or system error and the HTTP error code. The intParams may be nil if no integer parameters are required.
-// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
-func AllParams(req *http.Request, intParamNames []string) (map[string]string, map[string]int, error, error, int) {
-	params, err := GetCombinedParams(req)
-	if err != nil {
-		return nil, nil, errors.New("getting combined URI parameters: " + err.Error()), nil, http.StatusBadRequest
-	}
-	intParams, err := IntParams(params, intParamNames)
-	if err != nil {
-		return nil, nil, nil, errors.New("getting combined URI parameters: " + err.Error()), http.StatusInternalServerError
-	}
-	return params, intParams, nil, nil, 0
-}
diff --git a/traffic_ops/traffic_ops_golang/cdn/namedelete.go b/traffic_ops/traffic_ops_golang/cdn/namedelete.go
index 6fb438947..3d6cf5c6a 100644
--- a/traffic_ops/traffic_ops_golang/cdn/namedelete.go
+++ b/traffic_ops/traffic_ops_golang/cdn/namedelete.go
@@ -30,7 +30,7 @@ import (
 
 func DeleteName(db *sql.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
-		params, _, userErr, sysErr, errCode := api.AllParams(r, nil)
+		params, _, userErr, sysErr, errCode := api.AllParams(r, []string{"name"}, nil)
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go
index 6244acf8a..a4685a0d6 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go
@@ -355,7 +355,7 @@ func UpdateV13(db *sqlx.DB, cfg config.Config) http.HandlerFunc {
 			return
 		}
 
-		params, _, userErr, sysErr, errCode := api.AllParams(r, nil)
+		params, _, userErr, sysErr, errCode := api.AllParams(r, []string{"id"}, nil)
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyid.go b/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyid.go
index 19bdc903d..e039d1e53 100644
--- a/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyid.go
+++ b/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyid.go
@@ -30,7 +30,7 @@ import (
 
 func GetProfileID(db *sql.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
-		_, intParams, userErr, sysErr, errCode := api.AllParams(r, []string{"id"})
+		_, intParams, userErr, sysErr, errCode := api.AllParams(r, []string{"id"}, []string{"id"})
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyname.go b/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyname.go
index 3dd6f85a6..c89d452ad 100644
--- a/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyname.go
+++ b/traffic_ops/traffic_ops_golang/profileparameter/parameterprofilebyname.go
@@ -30,7 +30,7 @@ import (
 
 func GetProfileName(db *sql.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
-		params, _, userErr, sysErr, errCode := api.AllParams(r, nil)
+		params, _, userErr, sysErr, errCode := api.AllParams(r, []string{"name"}, nil)
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyid.go b/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyid.go
index 8c17b58ab..44d5298fa 100644
--- a/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyid.go
+++ b/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyid.go
@@ -35,7 +35,7 @@ import (
 func PostProfileParamsByID(db *sql.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		defer r.Body.Close()
-		_, intParams, userErr, sysErr, errCode := api.AllParams(r, []string{"id"})
+		_, intParams, userErr, sysErr, errCode := api.AllParams(r, []string{"id"}, []string{"id"})
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyname.go b/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyname.go
index a4fffdfc2..7326f5b36 100644
--- a/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyname.go
+++ b/traffic_ops/traffic_ops_golang/profileparameter/postprofileparametersbyname.go
@@ -36,7 +36,7 @@ import (
 func PostProfileParamsByName(db *sql.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		defer r.Body.Close()
-		params, _, userErr, sysErr, errCode := api.AllParams(r, nil)
+		params, _, userErr, sysErr, errCode := api.AllParams(r, []string{"name"}, nil)
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/profileparameter/unassignedparams.go b/traffic_ops/traffic_ops_golang/profileparameter/unassignedparams.go
index 79ecc81fb..14c7ba1bf 100644
--- a/traffic_ops/traffic_ops_golang/profileparameter/unassignedparams.go
+++ b/traffic_ops/traffic_ops_golang/profileparameter/unassignedparams.go
@@ -34,7 +34,7 @@ import (
 
 func GetUnassigned(db *sql.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
-		_, intParams, userErr, sysErr, errCode := api.AllParams(r, []string{"id"})
+		_, intParams, userErr, sysErr, errCode := api.AllParams(r, []string{"id"}, []string{"id"})
 		if userErr != nil || sysErr != nil {
 			api.HandleErr(w, r, errCode, userErr, sysErr)
 			return
diff --git a/traffic_ops/traffic_ops_golang/routing.go b/traffic_ops/traffic_ops_golang/routing.go
index c01239f62..bd647e24e 100644
--- a/traffic_ops/traffic_ops_golang/routing.go
+++ b/traffic_ops/traffic_ops_golang/routing.go
@@ -164,7 +164,7 @@ func CompileRoutes(routes map[string][]PathHandler) map[string][]CompiledRoute {
 }
 
 // Handler - generic handler func used by the Handlers hooking into the routes
-func Handler(routes map[string][]CompiledRoute, catchall http.Handler, w http.ResponseWriter, r *http.Request) {
+func Handler(routes map[string][]CompiledRoute, catchall http.Handler, db *sqlx.DB, cfg *config.Config, w http.ResponseWriter, r *http.Request) {
 	requested := r.URL.Path[1:]
 
 	mRoutes, ok := routes[r.Method]
@@ -178,16 +178,17 @@ func Handler(routes map[string][]CompiledRoute, catchall http.Handler, w http.Re
 		if len(match) == 0 {
 			continue
 		}
-
-		ctx := r.Context()
-
 		params := map[string]string{}
 		for i, v := range compiledRoute.Params {
 			params[v] = match[i+1]
 		}
 
+		ctx := r.Context()
 		ctx = context.WithValue(ctx, api.PathParamsKey, params)
-		compiledRoute.Handler(w, r.WithContext(ctx))
+		ctx = context.WithValue(ctx, api.DBContextKey, db)
+		ctx = context.WithValue(ctx, api.ConfigContextKey, cfg)
+		r = r.WithContext(ctx)
+		compiledRoute.Handler(w, r)
 		return
 	}
 	catchall.ServeHTTP(w, r)
@@ -209,7 +210,7 @@ func RegisterRoutes(d ServerData) error {
 	routes := CreateRouteMap(routeSlice, rawRoutes, authBase)
 	compiledRoutes := CompileRoutes(routes)
 	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
-		Handler(compiledRoutes, catchall, w, r)
+		Handler(compiledRoutes, catchall, d.DB, &d.Config, w, r)
 	})
 	return nil
 }


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services