-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
91 lines (71 loc) · 1.99 KB
/
main.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
package main
import (
"bytes"
"html/template"
"log"
"net/http"
"net/url"
"github.com/koseburak/marvel-universe-web/config"
"github.com/koseburak/marvel-universe-web/marvel"
"github.com/koseburak/marvel-universe-web/model"
)
var tpl = template.Must(template.ParseFiles("index.html"))
type Search struct {
Query string
TotalPages int
Results *model.MarvelResponse `json:"MarvelResponse"`
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
buf := &bytes.Buffer{}
err := tpl.Execute(buf, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
buf.WriteTo(w)
}
func searchHandler(marvelClient *marvel.MarvelClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
u, err := url.Parse(r.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
params := u.Query()
character := params.Get("character")
log.Println("Entered character: ", character)
resultCharacters, err := marvelClient.GetCharacters(character)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
search := &Search{
Query: character,
TotalPages: resultCharacters.Data.Total,
Results: resultCharacters,
}
buf := &bytes.Buffer{}
err = tpl.Execute(buf, search)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
buf.WriteTo(w)
}
}
func main() {
conf, err := config.Config()
if err != nil {
log.Println("Got error while loading env config: ", err)
}
log.Println(conf)
log.Println("Listening Serve Port: ", conf.Port)
defaultHTTPClient := &http.Client{}
marvelClient := marvel.NewMarvelClient(conf, defaultHTTPClient)
fs := http.FileServer(http.Dir("assets"))
mux := http.NewServeMux()
mux.Handle("/assets/", http.StripPrefix("/assets/", fs))
mux.HandleFunc("/", indexHandler)
mux.HandleFunc("/search", searchHandler(marvelClient))
http.ListenAndServe(":"+conf.Port, mux)
}