Skip to content

Commit c4fea37

Browse files
committed
json read & run a simple server
1 parent dcb6f2a commit c4fea37

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

json.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"os"
7+
)
8+
9+
type game struct {
10+
Name string
11+
Players int
12+
Seasons []string
13+
}
14+
15+
func main() {
16+
data, err := os.ReadFile("./files/test.json")
17+
if err != nil {
18+
panic(err)
19+
}
20+
21+
var game map[string]interface{}
22+
if err := json.Unmarshal(data, &game); err != nil {
23+
panic(err)
24+
}
25+
26+
fmt.Println(game)
27+
comp := game["name"]
28+
fmt.Println(comp)
29+
seasons := game["seasons"]
30+
fmt.Println(seasons)
31+
}

server.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"os"
7+
)
8+
9+
func main() {
10+
http.HandleFunc("/", hello)
11+
http.HandleFunc("/page", page)
12+
http.HandleFunc("/file", file)
13+
14+
http.ListenAndServe(":8090", nil)
15+
}
16+
17+
func hello(w http.ResponseWriter, req *http.Request) {
18+
fmt.Fprintf(w, "hello page\n")
19+
}
20+
21+
func page(w http.ResponseWriter, req *http.Request) {
22+
for name, headers := range req.Header {
23+
for _, header := range headers {
24+
fmt.Fprintf(w, "%v %v", name, header)
25+
}
26+
}
27+
}
28+
29+
func file(w http.ResponseWriter, req *http.Request) {
30+
data, err := os.ReadFile("./files/test.txt")
31+
if err != nil {
32+
fmt.Fprint(w, "Error: can't read file to show the content")
33+
}
34+
fmt.Fprintf(w, string(data))
35+
}

0 commit comments

Comments
 (0)