NewGit
Sign in
c492fe61
products.go 34 lines632 B
 1package main
 2
 3import (
 4	"encoding/json"
 5	"net/http"
 6	"strconv"
 7)
 8
 9type Product struct {
10	ID       int     `json:"id"`
11	Name     string  `json:"name"`
12	Price    float64 `json:"price"`
13	Discount float64 `json:"discount"`
14}
15
16var products = []Product{
17	{1, "Notebook", 4.50, 0},
18	{2, "Pen", 1.20, 0.1},
19	{3, "Backpack", 39.00, 0.25},
20}
21
22func listProducts(w http.ResponseWriter, r *http.Request) {
23	json.NewEncoder(w).Encode(products)
24}
25
26func getProduct(w http.ResponseWriter, r *http.Request) {
27	id, _ := strconv.Atoi(r.PathValue("id"))
28	for _, p := range products {
29		if p.ID == id {
30			json.NewEncoder(w).Encode(p)
31			return
32		}
33	}
34}