· 4 years ago · Aug 10, 2021, 06:52 PM
1
2package main
3
4import (
5 "fmt"
6 "log"
7 "net/http"
8 "io/ioutil"
9 "encoding/json"
10)
11
12type Bazaar struct{
13 Listings []Listing `json:"bazaar"`
14}
15
16type Listing struct{
17 Id int `json:"ID"`
18 Name string `json:"name"`
19 ItemType string `json:"type"`
20 Quantity int `json:"quantity"`
21 Price int `json:"price"`
22 MarketPrice int `json:"market_price"`
23}
24
25func getItems(player string) Bazaar{
26 //Your api key goes where the *********** are
27 res, err := http.Get("https://api.torn.com/user/"+player+"?selections=bazaar&key=*****************")
28 if err != nil{
29 log.Fatal(err)
30 }
31
32 if res.Body != nil{
33 defer res.Body.Close()
34 }
35
36 body, readErr := ioutil.ReadAll(res.Body)
37 if readErr != nil{
38 log.Fatal(readErr)
39 }
40 str := string(body[:])
41
42 fmt.Println(str)
43
44 var b Bazaar
45// var list []Listing
46// jsonErr := json.Unmarshal(body, &list) //&b)
47 jsonErr := json.Unmarshal(body, &b)
48 if jsonErr != nil{
49 log.Fatal(jsonErr)
50 }
51
52 fmt.Println(b)
53 return b
54}
55
56func handler( w http.ResponseWriter, r *http.Request){
57 items := getItems(r.URL.Path[1:])
58 fmt.Fprintf(w, "<html><head><title>Bazaar Viewer</title>")
59 fmt.Fprintf(w, `<style>
60 .container{
61 display:grid;
62 grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
63 grid-gap: 1rem;
64 }
65 .listing{
66 background-color: rgba(255, 255, 255, 0.8);
67 border: 1px solid rgba(0, 0, 0, 0.8);
68 padding: 20px;
69 font-size: 15px;
70 text-align: center;
71 }
72 </style>`)
73 fmt.Fprintf(w, "</head><body>")
74
75 fmt.Fprintf(w, "<div class='container'>")
76 for i := 0; i < len(items.Listings); i++{
77 fmt.Fprintf(w, "<div class='listing'>")
78 fmt.Fprintf(w, "<img src='https://www.torn.com/images/items/%d/large.png'>", items.Listings[i].Id)
79 fmt.Fprintf(w, "<div class='name'>%v</div>", items.Listings[i].Name)
80 fmt.Fprintf(w, "<div class='price'>$%v</div>", items.Listings[i].Price)
81 fmt.Fprintf(w, "<div class='quant'>X %v</div>", items.Listings[i].Quantity)
82 fmt.Fprintf(w, "</div>")
83 }
84 fmt.Fprintf(w, "</div>")
85 fmt.Fprintf(w, "</body></html>")
86}
87
88func main() {
89// getItems("1778676")
90 http.HandleFunc("/", handler)
91 log.Fatal(http.ListenAndServe(":8080", nil))
92}
93