API 서버 예제를 만들어 보려 합니다.
gin같은 좋은 웹프레임워크를 쓰면 좋지만 이번포스팅에서는 기본 패키지만 가지고 진행하겠습니다.
저는 백엔드를 익숙한 Django를 주로 쓰지만 언젠가는 Go로 전환하고 싶은 생각을 항상 합니다.
Django때문에 아직은 어렵겠지만요.
그래도 기본을 위해 포스팅 해봅니다.
한번에 다 포스팅 하기 힘들어서 계획을 잡고 하나씩 해볼까 합니다.
- API Mock서버로 테스트
- 실제 DB를 이용한 테스트
- 파일 다운로드, 파일 업로드
- 그다음 것 생각중...
HTTP 핸들러 함수가는 요청 처리 응답하는 함수입니다.
그래서 기능별로 URI를 등록해서 핸들러를 등록 하면서 API서버를 구축할 수 있습니다.
이번장은 API에 대한 기본적인 틀만 작성해 보았습니다.
테스트 요청은 다음과 명령어로 했습니다.
curl -X POST -H "Content-Type: application/json" -d '{"name":"iPhone19","mac":"11:11:11:22:22:22"}' http://localhost:8000/v1.0/device
{"messages":"Post success : 11:11:11:22:22:22","success":true}
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Device struct {
Id int `json:"id"`
Name string `json:"name"`
Mac string `json:"mac""`
}
func main() {
http.HandleFunc("/v1.0/device", func(res http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodPost {
// DB Insert는 다음에
var device Device
err := json.NewDecoder(req.Body).Decode(&device)
if err != nil {
res.WriteHeader(http.StatusBadRequest)
return
}
fmt.Printf("Name=%s,Mac=%s", device.Name, device.Mac)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
json.NewEncoder(res).Encode(map[string]interface{}{
"success": true,
"messages": fmt.Sprintf("Post success : %s", device.Mac),
})
} else if req.Method == http.MethodGet {
// DB select는 다음에
} else {
// 나머지 메소드는 거부로
res.WriteHeader(http.StatusMethodNotAllowed)
return
}
})
http.ListenAndServe(":8000", nil)
}