Permalink
Browse files

Linter fixes

  • Loading branch information...
brycekahle committed Jul 14, 2017
1 parent 93d4244 commit ba8d5bca3859284a49fcd3fdcb19887c253f1bd0
View
@@ -3,7 +3,7 @@
help: ## Show this help.
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {sub("\\\\n",sprintf("\n%22c"," "), $$2);printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
all: test build ## Run the tests and build the binary.
all: lint test build ## Run the tests and build the binary.
os = darwin
arch = amd64
View
@@ -96,7 +96,7 @@ func NewAPIWithVersion(ctx context.Context, config *conf.GlobalConfiguration, db
mux.Get("/downloads", api.DownloadList)
mux.Get("/orders/:order_id/downloads", api.DownloadList)
mux.Get("/vatnumbers/:number", api.VatnumberLookup)
mux.Get("/vatnumbers/:number", api.VatNumberLookup)
mux.Get("/payments", api.PaymentList)
mux.Get("/payments/:pay_id", api.PaymentView)
View
@@ -33,6 +33,7 @@ func (a *API) lookupCoupon(ctx context.Context, w http.ResponseWriter, code stri
return coupon, nil
}
// CouponView returns information about a single coupon code.
func (a *API) CouponView(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log := gcontext.GetLogger(ctx)
code := kami.Param(ctx, "code")
View
@@ -11,8 +11,9 @@ import (
"github.com/netlify/gocommerce/models"
)
const MaxIPsPerDay = 50
const maxIPsPerDay = 50
// DownloadURL returns a signed URL to download a purchased asset.
func (a *API) DownloadURL(ctx context.Context, w http.ResponseWriter, r *http.Request) {
id := kami.Param(ctx, "id")
log := gcontext.GetLogger(ctx).WithField("download_id", id)
@@ -66,9 +67,14 @@ func (a *API) DownloadURL(ctx context.Context, w http.ResponseWriter, r *http.Re
}
var count uint64
for rows.Next() {
rows.Scan(&count)
err = rows.Scan(&count)
if err != nil {
log.WithError(err).Warnf("Error while signing download: %s", err)
internalServerError(w, "Error signing download: %v", err)
return
}
}
if count > MaxIPsPerDay {
if count > maxIPsPerDay {
unauthorizedError(w, "This download has been accessed from too many IPs within the last day")
return
}
@@ -87,6 +93,7 @@ func (a *API) DownloadURL(ctx context.Context, w http.ResponseWriter, r *http.Re
sendJSON(w, http.StatusOK, download)
}
// DownloadList lists all purchased downloads for an order or a user.
func (a *API) DownloadList(ctx context.Context, w http.ResponseWriter, r *http.Request) {
orderID := kami.Param(ctx, "order_id")
log := gcontext.GetLogger(ctx)
View
@@ -4,22 +4,13 @@ import (
"encoding/json"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/netlify/gocommerce/claims"
"github.com/Sirupsen/logrus"
)
func sendJSON(w http.ResponseWriter, status int, obj interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
encoder := json.NewEncoder(w)
encoder.Encode(obj)
}
func userIDFromToken(token *jwt.Token) string {
if token == nil {
return ""
if err := json.NewEncoder(w).Encode(obj); err != nil {
logrus.WithError(err).Errorf("Error encoding json response: %v", obj)
}
claims := token.Claims.(*claims.JWTClaims)
return claims.ID
}
View
@@ -22,19 +22,19 @@ import (
// MaxConcurrentLookups controls the number of simultaneous HTTP Order lookups
const MaxConcurrentLookups = 10
type OrderLineItem struct {
type orderLineItem struct {
Sku string `json:"sku"`
Path string `json:"path"`
Quantity uint64 `json:"quantity"`
Addons []OrderAddon `json:"addons"`
Addons []orderAddon `json:"addons"`
MetaData map[string]interface{} `json:"meta"`
}
type OrderAddon struct {
type orderAddon struct {
Sku string `json:"sku"`
}
type OrderParams struct {
type orderRequestParams struct {
SessionID string `json:"session_id"`
Email string `json:"email"`
@@ -51,7 +51,7 @@ type OrderParams struct {
MetaData map[string]interface{} `json:"meta"`
LineItems []*OrderLineItem `json:"line_items"`
LineItems []*orderLineItem `json:"line_items"`
Currency string `json:"currency"`
@@ -60,7 +60,7 @@ type OrderParams struct {
CouponCode string `json:"coupon"`
}
type ReceiptParams struct {
type receiptParams struct {
Email string `json:"email"`
}
@@ -148,12 +148,13 @@ func (a *API) ClaimOrders(ctx context.Context, w http.ResponseWriter, r *http.Re
sendJSON(w, http.StatusNoContent, "")
}
// ResendOrderReceipt resends the email receipt for an order
func (a *API) ResendOrderReceipt(ctx context.Context, w http.ResponseWriter, r *http.Request) {
id := kami.Param(ctx, "order_id")
log := gcontext.GetLogger(ctx)
claims := gcontext.GetClaims(ctx)
params := &ReceiptParams{}
params := &receiptParams{}
jsonDecoder := json.NewDecoder(r.Body)
err := jsonDecoder.Decode(params)
if err != nil {
@@ -208,6 +209,7 @@ func (a *API) ResendOrderReceipt(ctx context.Context, w http.ResponseWriter, r *
// - email
// - items
// OrderList lists orders selected by the query parameters provided.
func (a *API) OrderList(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log := gcontext.GetLogger(ctx)
@@ -305,7 +307,7 @@ func (a *API) OrderCreate(ctx context.Context, w http.ResponseWriter, r *http.Re
log := gcontext.GetLogger(ctx)
config := gcontext.GetConfig(ctx)
params := &OrderParams{Currency: "USD"}
params := &orderRequestParams{Currency: "USD"}
jsonDecoder := json.NewDecoder(r.Body)
err := jsonDecoder.Decode(params)
if err != nil {
@@ -433,7 +435,7 @@ func (a *API) OrderUpdate(ctx context.Context, w http.ResponseWriter, r *http.Re
return
}
orderParams := new(OrderParams)
orderParams := new(orderRequestParams)
err := json.NewDecoder(r.Body).Decode(orderParams)
if err != nil {
log.WithError(err).Infof("Failed to deserialize order params: %s", err.Error())
@@ -559,7 +561,7 @@ func (a *API) OrderUpdate(ctx context.Context, w http.ResponseWriter, r *http.Re
//
// handle the line items
//
updatedItems := make(map[string]*OrderLineItem)
updatedItems := make(map[string]*orderLineItem)
for _, item := range orderParams.LineItems {
updatedItems[item.Sku] = item
}
@@ -640,7 +642,7 @@ func setOrderEmail(tx *gorm.DB, order *models.Order, claims *claims.JWTClaims, l
return nil
}
func (a *API) createLineItems(ctx context.Context, tx *gorm.DB, order *models.Order, items []*OrderLineItem) *HTTPError {
func (a *API) createLineItems(ctx context.Context, tx *gorm.DB, order *models.Order, items []*orderLineItem) *HTTPError {
sem := make(chan int, MaxConcurrentLookups)
var wg sync.WaitGroup
sharedErr := verificationError{}
@@ -655,7 +657,7 @@ func (a *API) createLineItems(ctx context.Context, tx *gorm.DB, order *models.Or
order.LineItems = append(order.LineItems, lineItem)
sem <- 1
wg.Add(1)
go func(item *models.LineItem, orderItem *OrderLineItem) {
go func(item *models.LineItem, orderItem *orderLineItem) {
defer func() {
wg.Done()
<-sem
@@ -751,7 +753,7 @@ func (a *API) processAddress(tx *gorm.DB, order *models.Order, name string, addr
return address, nil
}
func (a *API) processLineItem(ctx context.Context, order *models.Order, item *models.LineItem, orderItem *OrderLineItem) error {
func (a *API) processLineItem(ctx context.Context, order *models.Order, item *models.LineItem, orderItem *orderLineItem) error {
config := gcontext.GetConfig(ctx)
jwtClaims := gcontext.GetClaimsAsMap(ctx)
resp, err := a.httpClient.Get(config.SiteURL + item.Path)
View
@@ -44,8 +44,7 @@ func TestOrderCreationWithSimpleOrder(t *testing.T) {
order := &models.Order{}
extractPayload(t, http.StatusCreated, recorder, order)
var total uint64
total = 999
var total uint64 = 999
assert.Equal(t, "info@example.com", order.Email, "Total should be info@example.com, was %v", order.Email)
assert.Equal(t, total, order.Total, fmt.Sprintf("Total should be 999, was %v", order.Total))
if len(order.LineItems) != 1 {
@@ -84,10 +83,8 @@ func TestOrderCreationWithTaxes(t *testing.T) {
order := &models.Order{}
extractPayload(t, http.StatusCreated, recorder, order)
var total uint64
total = 1069
var taxes uint64
taxes = 70
var total uint64 = 1069
var taxes uint64 = 70
assert.Equal(t, "info@example.com", order.Email, "Total should be info@example.com, was %v", order.Email)
assert.Equal(t, "Germany", order.ShippingAddress.Country)
assert.Equal(t, "Germany", order.BillingAddress.Country)
@@ -117,10 +114,8 @@ func TestOrderCreationForBundleWithTaxes(t *testing.T) {
order := &models.Order{}
extractPayload(t, http.StatusCreated, recorder, order)
var total uint64
total = 1105
var taxes uint64
taxes = 106
var total uint64 = 1105
var taxes uint64 = 106
assert.Equal(t, "info@example.com", order.Email, "Total should be info@example.com, was %v", order.Email)
assert.Equal(t, "Germany", order.ShippingAddress.Country)
assert.Equal(t, "Germany", order.BillingAddress.Country)
@@ -471,7 +466,7 @@ func TestOrderUpdateFields(t *testing.T) {
defer db.Save(firstOrder)
assert := assert.New(t)
recorder := runUpdate(t, db, firstOrder, &OrderParams{
recorder := runUpdate(t, db, firstOrder, &orderRequestParams{
Email: "mrfreeze@dc.com",
Currency: "monopoly-dollars",
})
@@ -504,17 +499,17 @@ func TestOrderUpdateAddress_ExistingAddress(t *testing.T) {
newAddr := getTestAddress()
newAddr.ID = "new-addr"
newAddr.UserID = firstOrder.UserID
rsp := db.Create(newAddr)
db.Create(newAddr)
defer db.Unscoped().Delete(newAddr)
recorder := runUpdate(t, db, firstOrder, &OrderParams{
recorder := runUpdate(t, db, firstOrder, &orderRequestParams{
BillingAddressID: newAddr.ID,
})
rspOrder := new(models.Order)
extractPayload(t, http.StatusOK, recorder, rspOrder)
saved := new(models.Order)
rsp = db.First(saved, "id = ?", firstOrder.ID)
rsp := db.First(saved, "id = ?", firstOrder.ID)
assert.False(rsp.RecordNotFound())
// now we load the addresses
@@ -534,7 +529,7 @@ func TestOrderUpdateAddress_NewAddress(t *testing.T) {
assert := assert.New(t)
paramsAddress := getTestAddress()
recorder := runUpdate(t, db, firstOrder, &OrderParams{
recorder := runUpdate(t, db, firstOrder, &orderRequestParams{
// should create a new address associated with the order's user
ShippingAddress: paramsAddress,
})
@@ -561,7 +556,7 @@ func TestOrderUpdateAsNonAdmin(t *testing.T) {
ctx := testContext(testToken("villian", "villian@wayneindustries.com"), config, false)
ctx = kami.SetParam(ctx, "id", firstOrder.ID)
params := &OrderParams{
params := &orderRequestParams{
Email: "mrfreeze@dc.com",
Currency: "monopoly-dollars",
}
@@ -584,7 +579,7 @@ func TestOrderUpdateWithNoCreds(t *testing.T) {
ctx := testContext(nil, config, false)
ctx = kami.SetParam(ctx, "id", firstOrder.ID)
params := &OrderParams{
params := &orderRequestParams{
Email: "mrfreeze@dc.com",
Currency: "monopoly-dollars",
}
@@ -605,7 +600,7 @@ func TestOrderUpdateWithNoCreds(t *testing.T) {
func TestOrderUpdateWithNewData(t *testing.T) {
db, _, _ := db(t)
assert := assert.New(t)
op := &OrderParams{
op := &orderRequestParams{
MetaData: map[string]interface{}{
"thing": float64(1),
"red": "fish",
@@ -709,7 +704,7 @@ func TestClaimOrdersMultipleTimes(t *testing.T) {
// HELPERS
// -------------------------------------------------------------------------------------------------------------------
func runUpdate(t *testing.T, db *gorm.DB, order *models.Order, params *OrderParams) *httptest.ResponseRecorder {
func runUpdate(t *testing.T, db *gorm.DB, order *models.Order, params *orderRequestParams) *httptest.ResponseRecorder {
globalConfig, config := testConfig()
ctx := testContext(testToken("admin-yo", "admin@wayneindustries.com"), config, true)
ctx = kami.SetParam(ctx, "id", order.ID)
View
@@ -9,7 +9,7 @@ import (
"github.com/jinzhu/gorm"
)
const DEFAULT_PER_PAGE = 50
const defaultPerPage = 50
func calculateTotalPages(perPage, total uint64) uint64 {
pages := total / perPage
@@ -42,7 +42,7 @@ func paginate(w http.ResponseWriter, r *http.Request, query *gorm.DB) (offset in
queryPage := params.Get("page")
queryPerPage := params.Get("per_page")
var page uint64 = 1
var perPage uint64 = DEFAULT_PER_PAGE
var perPage uint64 = defaultPerPage
if queryPage != "" {
page, err = strconv.ParseUint(queryPage, 10, 64)
if err != nil {
View
@@ -11,6 +11,11 @@ import (
"github.com/netlify/gocommerce/models"
)
type sortDirection string
const ascending sortDirection = "asc"
const descending sortDirection = "desc"
var sortFields = map[string]string{
"created_at": "created_at",
"updated_at": "updated_at",
@@ -63,8 +68,7 @@ func parseUserQueryParams(query *gorm.DB, params url.Values) (*gorm.DB, error) {
}
func sortField(value string) string {
field, _ := sortFields[value]
return field
return sortFields[value]
}
func parseOrderParams(query *gorm.DB, params url.Values) (*gorm.DB, error) {
@@ -99,18 +103,18 @@ func parseOrderParams(query *gorm.DB, params url.Values) (*gorm.DB, error) {
if field == "" {
return nil, fmt.Errorf("bad field for sort '%v'", field)
}
dir := "asc"
dir := ascending
if len(parts) == 2 {
switch strings.ToLower(parts[1]) {
case "asc":
dir = "asc"
case "desc":
dir = "desc"
case string(ascending):
dir = ascending
case string(descending):
dir = descending
default:
return nil, fmt.Errorf("bad direction for sort '%v', only 'asc' and 'desc' allowed", parts[1])
}
}
query = query.Order(field + " " + dir)
query = query.Order(field + " " + string(dir))
}
} else {
fmt.Println("Sorting by created_at desc")
Oops, something went wrong.

0 comments on commit ba8d5bc

Please sign in to comment.