forked from pion/webrtc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples.go
98 lines (83 loc) · 2.24 KB
/
examples.go
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"encoding/json"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
// Examples represents the examples loaded from examples.json.
type Examples []Example
// Examples represents an example loaded from examples.json.
type Example struct {
Title string `json:"title"`
Link string `json:"link"`
Description string `json:"description"`
Type string `json:"type"`
}
func main() {
addr := flag.String("address", ":80", "Address to host the HTTP server on.")
flag.Parse()
log.Println("Listening on", *addr)
err := serve(*addr)
if err != nil {
log.Fatalf("Failed to serve: %v", err)
}
}
func serve(addr string) error {
// Load the examples
examples, err := getExamples()
if err != nil {
return err
}
// Load the templates
homeTemplate := template.Must(template.ParseFiles("index.html"))
// Serve the required pages
// DIY 'mux' to avoid additional dependencies
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) > 3 && // 1 / example:2 / link:3 / [ static: 4 ]
parts[1] == "example" {
exampleLink := parts[2]
for _, example := range *examples {
if example.Link != exampleLink {
continue
}
fiddle := filepath.Join(exampleLink, "jsfiddle")
if len(parts[3]) != 0 {
http.StripPrefix("/example/"+exampleLink+"/", http.FileServer(http.Dir(fiddle))).ServeHTTP(w, r)
return
}
temp := template.Must(template.ParseFiles("example.html"))
_, err = temp.ParseFiles(filepath.Join(fiddle, "demo.html"))
if err != nil {
panic(err)
}
temp.Execute(w, example)
return
}
}
// Serve the main page
homeTemplate.Execute(w, examples)
})
// Start the server
return http.ListenAndServe(addr, nil)
}
// getExamples loads the examples from the examples.json file.
func getExamples() (*Examples, error) {
file, err := os.Open("./examples.json")
defer file.Close()
if err != nil {
return nil, fmt.Errorf("failed to list examples (please run in the examples folder): %v", err)
}
var examples Examples
err = json.NewDecoder(file).Decode(&examples)
if err != nil {
return nil, fmt.Errorf("failed to parse examples: %v", err)
}
return &examples, nil
}