Skip to content

Commit 40a28c9

Browse files
committed
json file and server
1 parent c00ac18 commit 40a28c9

File tree

2 files changed

+11901
-0
lines changed

2 files changed

+11901
-0
lines changed

server.go

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"io/ioutil"
7+
"log"
8+
"net/http"
9+
"os"
10+
11+
"github.com/gorilla/mux"
12+
)
13+
14+
type Superhero struct {
15+
ID int `json:"id"`
16+
Name string `json:"name"`
17+
Slug string `json:"slug"`
18+
Intelligence int `json:"intelligence"`
19+
Strength int `json:"strength"`
20+
Speed int `json:"speed"`
21+
Durability int `json:"durability"`
22+
Power int `json:"power"`
23+
Combat int `json:"combat"`
24+
Gender string `json:"gender"`
25+
Race string `json:"race"`
26+
Height string `json:"height"`
27+
Weight string `json:"weight"`
28+
FullName string `json:"fullName"`
29+
PlaceOfBirth string `json:"placeOfBirth"`
30+
FirstAppearance string `json:"firstAppearance"`
31+
Publisher string `json:"publisher"`
32+
Alignment string `json:"alignment"`
33+
Sm string `json:"sm"`
34+
}
35+
36+
var superheroes []Superhero
37+
38+
func handleError(err error) {
39+
if err != nil {
40+
log.Panic(err)
41+
}
42+
}
43+
44+
// all Get handlers
45+
func getHeroes(w http.ResponseWriter, r *http.Request) {
46+
w.Header().Set("Content-Type", "application/json")
47+
json.NewEncoder(w).Encode(superheroes)
48+
}
49+
50+
func getJSON(jsonfile string) {
51+
jsonFile, err := os.Open(jsonfile)
52+
handleError(err)
53+
54+
// read our opened xml/json as a byte array.
55+
byteValue, err := ioutil.ReadAll(jsonFile)
56+
handleError(err)
57+
58+
err = json.Unmarshal(byteValue, &superheroes)
59+
handleError(err)
60+
fmt.Println(superheroes)
61+
62+
jsonFile.Close()
63+
}
64+
65+
func main() {
66+
r := mux.NewRouter()
67+
68+
getJSON("./superheroAPI.json")
69+
70+
fmt.Println()
71+
72+
//Route Handlers / Endpoints
73+
r.HandleFunc("/api/superhero", getHeroes).Methods("GET")
74+
75+
fmt.Println("Server running on port 8080")
76+
log.Fatal(http.ListenAndServe(":8080", r))
77+
}

0 commit comments

Comments
 (0)