GetStudentListHandler() 함수는 학생정보를 가져와서 JSON포맷으로 만들어주는 함수이다.
//ch30/ex30.1/ex30.1.go
package main
import (
"encoding/json"
"net/http"
"sort"
"github.com/gorilla/mux"
)
type Student struct {
Id int
Name string
Age int
Score int
}
var students map[int]Student // ❶ 학생 목록을 저장하는 맵
var lastId int
func MakeWebHandler() http.Handler {
mux := mux.NewRouter() // ❷ gorilla/mux를 만듭니다.
mux.HandleFunc("/students", GetStudentListHandler).Methods("GET")
//-- ❸ 여기에 새로운 핸들러 등록 --//
students = make(map[int]Student) // ❹ 임시 데이터 생성
students[1] = Student{1, "aaa", 16, 87}
students[2] = Student{2, "bbb", 18, 98}
lastId = 2
return mux
}
type Students []Student // Id로 정렬하는 인터페이스
func (s Students) Len() int {
return len(s)
}
func (s Students) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Students) Less(i, j int) bool {
return s[i].Id < s[j].Id
}
func GetStudentListHandler(w http.ResponseWriter, r *http.Request) {
list := make(Students, 0) // ➎ 학생 목록을 Id로 정렬
for _, student := range students {
list = append(list, student)
}
sort.Sort(list)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(list) // ➏ JSON 포맷으로 변경
}
func main() {
http.ListenAndServe(":3000", MakeWebHandler())
}
30.4 테스트 코드 작성하기
//ch30/ex30.1/ex30_1_test.go
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestJsonHandler(t *testing.T) {
assert := assert.New(t)
res := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/students", nil) // ❶ /students 경로 테스트
mux := MakeWebHandler()
mux.ServeHTTP(res, req)
assert.Equal(http.StatusOK, res.Code)
var list []Student
err := json.NewDecoder(res.Body).Decode(&list) // ❷ 결과 변환
assert.Nil(err) // ❸ 결과 확인
assert.Equal(2, len(list))
assert.Equal("aaa", list[0].Name)
assert.Equal("bbb", list[1].Name)
}
// ch30/ex30.2/ex30.2.go
package main
import (
"encoding/json"
"net/http"
"sort"
"strconv"
"github.com/gorilla/mux"
)
type Student struct {
Id int
Name string
Age int
Score int
}
var students map[int]Student // ❶ 학생 목록을 저장하는 맵
var lastId int
func MakeWebHandler() http.Handler {
mux := mux.NewRouter() // ❷ gorilla/mux를 만듭니다.
mux.HandleFunc("/students", GetStudentListHandler).Methods("GET")
//-- ❸ 여기에 새로운 핸들러 등록 --//
mux.HandleFunc("/students/{id:[0-9]+}", GetStudentHandler).Methods("GET")
students = make(map[int]Student) // ❹ 임시 데이터 생성
students[1] = Student{1, "aaa", 16, 87}
students[2] = Student{2, "bbb", 18, 98}
lastId = 2
return mux
}
type Students []Student // Id로 정렬하는 인터페이스
func (s Students) Len() int {
return len(s)
}
func (s Students) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Students) Less(i, j int) bool {
return s[i].Id < s[j].Id
}
func GetStudentListHandler(w http.ResponseWriter, r *http.Request) {
list := make(Students, 0) // ➎ 학생 목록을 Id로 정렬
for _, student := range students {
list = append(list, student)
}
sort.Sort(list)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(list) // ➏ JSON 포맷으로 변경
}
func GetStudentHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) // ❶ id를 가져옵니다.
id, _ := strconv.Atoi(vars["id"])
student, ok := students[id]
if !ok {
w.WriteHeader(http.StatusNotFound) // ❷ id에 해당하는 학생이 없으면 에러
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(student)
}
func main() {
http.ListenAndServe(":3100", MakeWebHandler())
}
//ch30/ex30.2/ex30_2_test.go
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestJsonHandler(t *testing.T) {
assert := assert.New(t)
res := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/students", nil) // ❶ /students 경로 테스트
mux := MakeWebHandler()
mux.ServeHTTP(res, req)
assert.Equal(http.StatusOK, res.Code)
var list []Student
err := json.NewDecoder(res.Body).Decode(&list) // ❷ 결과 변환
assert.Nil(err) // ❸ 결과 확인
assert.Equal(2, len(list))
assert.Equal("aaa", list[0].Name)
assert.Equal("bbb", list[1].Name)
}
func TestJsonHandler2(t *testing.T) {
assert := assert.New(t)
var student Student
mux := MakeWebHandler()
res := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/students/1", nil) // ❶ id 1 학생
mux.ServeHTTP(res, req)
assert.Equal(http.StatusOK, res.Code)
err := json.NewDecoder(res.Body).Decode(&student)
assert.Nil(err)
assert.Equal("aaa", student.Name)
res = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/students/2", nil) // ❷ id 2 학생
mux.ServeHTTP(res, req)
assert.Equal(http.StatusOK, res.Code)
err = json.NewDecoder(res.Body).Decode(&student)
assert.Nil(err)
assert.Equal("bbb", student.Name)
}