Mode:
Duration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main
import (
"fmt"
"net/http"
"sort"
)
type Product struct {
Name string
Price int
}
var products = []Product{
{Name: "Laptop", Price: 1200},
{Name: "Phone", Price: 800},
{Name: "Tablet", Price: 500},
}
func productsHandler(w http.ResponseWriter, r *http.Request) {
order := r.URL.Query().Get("sort")
sort.Slice(products, func(i, j int) bool {
if order == "price" {
return products[i].Price < products[j].Price
}
return products[i].Name < products[j].Name
})
fmt.Fprintln(w, products)
}
func main() {
http.HandleFunc("/products", productsHandler)
fmt.Println("Sorting API running on :8080")
http.ListenAndServe(":8080", nil)
}Coding works best on desktop or with an external keyboard.