Skip to content

Commit bf7fa2d

Browse files
committed
Refactor code to doing testeable
1 parent a981e00 commit bf7fa2d

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

pkg/server/api.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,20 @@ type api struct {
1414
repository gopher.GopherRepository
1515
}
1616

17+
// Server representation of gopher server
1718
type Server interface {
1819
Router() http.Handler
20+
FetchGophers(w http.ResponseWriter, r *http.Request)
21+
FetchGopher(w http.ResponseWriter, r *http.Request)
1922
}
2023

24+
// New initialize the server
2125
func New(repo gopher.GopherRepository) Server {
2226
a := &api{repository: repo}
2327

2428
r := mux.NewRouter()
25-
r.HandleFunc("/gophers", a.fetchGophers).Methods(http.MethodGet)
26-
r.HandleFunc("/gophers/{ID:[a-zA-Z0-9_]+}", a.fetchGopher).Methods(http.MethodGet)
29+
r.HandleFunc("/gophers", a.FetchGophers).Methods(http.MethodGet)
30+
r.HandleFunc("/gophers/{ID:[a-zA-Z0-9_]+}", a.FetchGopher).Methods(http.MethodGet)
2731

2832
a.router = r
2933
return a
@@ -33,14 +37,16 @@ func (a *api) Router() http.Handler {
3337
return a.router
3438
}
3539

36-
func (a *api) fetchGophers(w http.ResponseWriter, r *http.Request) {
40+
// FetchGophers return a list of all gophers
41+
func (a *api) FetchGophers(w http.ResponseWriter, r *http.Request) {
3742
gophers, _ := a.repository.FetchGophers()
3843

3944
w.Header().Set("Content-Type", "application/json")
4045
json.NewEncoder(w).Encode(gophers)
4146
}
4247

43-
func (a *api) fetchGopher(w http.ResponseWriter, r *http.Request) {
48+
// FetchGopher return a gopher by ID
49+
func (a *api) FetchGopher(w http.ResponseWriter, r *http.Request) {
4450
vars := mux.Vars(r)
4551
gopher, err := a.repository.FetchGopherByID(vars["ID"])
4652
w.Header().Set("Content-Type", "application/json")

0 commit comments

Comments
 (0)