package main import ( "log" "net/http" "time" "git.k6n.net/go-cart-actor/pkg/cart" "github.com/matst80/go-redis-inventory/pkg/inventory" ) func getCurrency(country string) string { if country == "no" { return "NOK" } return "SEK" } func getLocale(country string) string { if country == "no" { return "nb-no" } return "sv-se" } func getLocationId(item *cart.CartItem) inventory.LocationID { if item.StoreId == nil || *item.StoreId == "" { return "se" } return inventory.LocationID(*item.StoreId) } func getInventoryRequests(items []*cart.CartItem) []inventory.ReserveRequest { var requests []inventory.ReserveRequest for _, item := range items { if item == nil { continue } requests = append(requests, inventory.ReserveRequest{ InventoryReference: &inventory.InventoryReference{ SKU: inventory.SKU(item.Sku), LocationID: getLocationId(item), }, Quantity: uint32(item.Quantity), }) } return requests } func getOriginalHost(r *http.Request) string { proxyHost := r.Header.Get("X-Forwarded-Host") if proxyHost != "" { return proxyHost } return r.Host } func getClientIp(r *http.Request) string { ip := r.Header.Get("X-Forwarded-For") if ip == "" { ip = r.RemoteAddr } return ip } func CookieCartIdHandler(fn func(cartId cart.CartId, w http.ResponseWriter, r *http.Request) error) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { var id cart.CartId cookie, err := r.Cookie("cartid") if err != nil || cookie.Value == "" { id = cart.MustNewCartId() http.SetCookie(w, &http.Cookie{ Name: "cartid", Value: id.String(), Secure: r.TLS != nil, HttpOnly: true, Path: "/", Expires: time.Now().AddDate(0, 0, 14), SameSite: http.SameSiteLaxMode, }) w.Header().Set("Set-Cart-Id", id.String()) } else { parsed, ok := cart.ParseCartId(cookie.Value) if !ok { id = cart.MustNewCartId() http.SetCookie(w, &http.Cookie{ Name: "cartid", Value: id.String(), Secure: r.TLS != nil, HttpOnly: true, Path: "/", Expires: time.Now().AddDate(0, 0, 14), SameSite: http.SameSiteLaxMode, }) w.Header().Set("Set-Cart-Id", id.String()) } else { id = parsed } } err = fn(id, w, r) if err != nil { log.Printf("Server error, not remote error: %v\n", err) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) } } } func CartIdHandler(fn func(cartId cart.CartId, w http.ResponseWriter, r *http.Request) error) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { var id cart.CartId raw := r.PathValue("id") // If no id supplied, generate a new one if raw == "" { id := cart.MustNewCartId() w.Header().Set("Set-Cart-Id", id.String()) } else { // Parse base62 cart id if parsedId, ok := cart.ParseCartId(raw); !ok { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("cart id is invalid")) return } else { id = parsedId } } err := fn(id, w, r) if err != nil { log.Printf("Server error, not remote error: %v\n", err) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) } } }