generated from gopherdojo/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
51 lines (40 loc) · 932 Bytes
/
server.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
package server
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/gopherdojo/dojo8/kadai4/hokita/omikuji/omikuji"
)
type Omikuji interface {
Draw() *omikuji.Result
}
type Server struct {
Omikuji Omikuji
}
func Run() {
os.Exit(run())
}
func run() int {
server := &Server{NewOmikuji()}
if err := http.ListenAndServe(":8080", server); err != nil {
fmt.Fprintf(os.Stderr, "could not listen on port 8080 %v\n", err)
return 1
}
return 0
}
func NewOmikuji() Omikuji {
return omikuji.New(time.Now())
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
router := http.NewServeMux()
router.Handle("/omikuji/", http.HandlerFunc(s.omikujiHandler))
router.ServeHTTP(w, r)
}
func (s *Server) omikujiHandler(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(s.Omikuji.Draw()); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}