Created
May 5, 2022 21:53
-
-
Save phrozen/232add9852c626ead3856e5d02a039aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"math/rand" | |
"net/http" | |
"strings" | |
"time" | |
"github.com/go-chi/chi/v5" | |
"github.com/go-chi/chi/v5/middleware" | |
"github.com/google/uuid" | |
) | |
type OrderStatusResponse struct { | |
ID string `json:"id"` | |
Status string `json:"status"` | |
Amount string `json:"amount"` | |
CreatedAt time.Time `json:"createdAt"` | |
UpdatedAt time.Time `json:"updatedAt"` | |
} | |
func GetOrderStatusById(id string) *OrderStatusResponse { | |
osr := &OrderStatusResponse{ID: id} | |
status := []string{"PAYMENT", "PROCESSING", "SHIPMENT", "TRANSIT", "FULLFILLED", "PENDING", "SUPPORT"} | |
osr.Status = status[rand.Intn(len(status))] | |
osr.Amount = fmt.Sprintf("$%.2f", float64(rand.Intn(1000000))/100) | |
osr.CreatedAt = time.Now().Add(time.Duration(-rand.Intn(90*60*60*24))*time.Second - (15 * 24 * time.Hour)) | |
osr.UpdatedAt = osr.CreatedAt.Add(time.Duration(rand.Intn(20*60*60*24))*time.Second + (24 * time.Hour)) | |
return osr | |
} | |
func main() { | |
r := chi.NewRouter() | |
r.Use(middleware.Logger) | |
r.Use(middleware.Recoverer) | |
r.Get("/orders/pending", func(w http.ResponseWriter, r *http.Request) { | |
ids := make([]string, 1000) | |
for i := range ids { | |
ids[i] = uuid.NewString() | |
} | |
w.Write([]byte(strings.Join(ids, "\n"))) | |
}) | |
r.Get("/orders/status/{id}", func(w http.ResponseWriter, r *http.Request) { | |
time.Sleep(50 * time.Millisecond) | |
id, err := uuid.Parse(chi.URLParam(r, "id")) | |
if err != nil { | |
w.WriteHeader(http.StatusBadRequest) | |
w.Write([]byte("Invalid uuid")) | |
return | |
} | |
order := GetOrderStatusById(id.String()) | |
w.Header().Add("Content-Type", "application/json") | |
json.NewEncoder(w).Encode(order) | |
}) | |
http.ListenAndServe(":3333", r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment