전체보기

    [바미] Go - Template

    Template? 쉽게 얘기하면 어떤 틀을 의미합니다. 코드로 알아보면 main.go package main import "html/template" type User struct { Name string Email string Age int } func main() { user := User{Name: "changbeom", Email: "changbeom@naver.com", Age: 23} tmpl, err := template.New("Tmp11").Parse("Name: {{.Name}}\nEmail: {{.Email}}\nAge: {{.Age}}") // 1 if err != nil { panic(err) } tmpl.Execute(os.Stdout, user) // 2 1 : Tmp11라는 ..

    [바미] Go - SQL query(CRUD)

    model/model.go package model import "time" type Todo struct { ID int `json:"id"` Name string `json:"name"` Completed bool `json:"completed"` CreatedAt time.Time `json:"created_at"` } type DbHandler interface { GetTodos() []*Todo AddTodo(name string) *Todo RemoveTodo(id int) bool CompleteTodo(id int, complete bool) bool // 1 close() } // var handler DbHandler func NewDBHandler() DBHandler { // 2 ..

    [바미] Go - Render, Pat, Negroni

    먼저 심플한 코드 부터 작성 해봅시다! main.go package main type User struct { Name string `json:"name"` Email string `json:"email"` CreatedAt time.Time `json:"created_at"` } func getUserInfoHandler(w http.ResponseWriter, r *http.Request) { user := User{Name: "turcker", Email: "turcker@naver.com"} w.Header().Add("Content-type", "application/json") w.WriteHeader(http.StatusOK) data, _ := json.Marshal(user) fmt.Fp..

    [바미] Go - Decorator 패턴

    Decorator? 기본 기능에 추가할 수 있는 많은 종류의 부가 기능에서 파생되는 다양한 조합을 동적으로 구현할 수 있는 패턴입니다. 실제 예로 들면 Data를 어떤 사람에게 보낼려 할 때 '압축'을 해서 보낸다던지, '암호화'를 해서 보낸다던지, 나중에 추적할 수 있도록'log'를 단다던지, 마케팅 서버가 있다면 그 곳에 보낸다던지, 등의 기능들이 추가 되는 것이 Decorator입니다. 그렇다면 왜 Decorator를 사용할까요? 앞서 설명했던 '압축', '암호화', 'log', '마케팅요소'등을 하나로 뭉쳐서 만들 수도 있지만 이 부가 기능들은 대체로 잘 바뀌는 특성이 있습니다. 그래서 Data(오리지날 기능)는 바뀌지 않는데, 부가 기능들이 바뀔 때 마다 다 바꾸어 주어야 하기 때문이며, 이는 ..

    [바미] Go - RESTful API(PUT, GET list)

    먼저 테스트 코드 부터 작성하고 시작합시다! myapp/app_test.go 맨 아래에 추가해줍니다. func TestUpdateUser(t *testing.T) { assert := assert.New(t) ts := httptest.NewServer(NewHandler()) defer ts.Close() req, _ := http.NewRequest("PUT", ts.URL+"/users", strings.NewReader(`{"id":1, "first_name":"changbeom", "last_name":"song", "email":"changbeom@naver.com"}`))) resp, err := http.DefaultClient.Do(req) assert.NoError(err) assert..

    [바미] Go - RESTful API(DELETE)

    기존에 있는 코드에 이어서 테스트 코드 부터 만들어 줍니다. myapp/app_test.go package myapp import ( "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "strconv" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestIndex(t *testing.T) { assert := assert.New(t) ts := httptest.NewServer(NewHandler()) defer ts.Close() resp, err := http.Get(ts.URL) assert.NoError(err) assert.Equal(http.StatusOK, resp.S..

    [바미] Go - RESTful API(POST)

    GET에 이어서 myapp/app_test.go를 수정 해줍니다. myapp/app_test.go package myapp import ( "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestIndex(t *testing.T) { assert := assert.New(t) ts := httptest.NewServer(NewHandler()) defer ts.Close() resp, err := http.Get(ts.URL) assert.NoError(err) assert.Equal(http.StatusOK, resp.StatusCode) data, _ := ioutil.Read..

    [바미] Go - RESTful API(GET)

    먼저 기본틀을 만들고 시작합니다. 그 전에 Handler를 만들어 주어야 하는데 'myapp'이라는 폴더에 app.go라는 파일에 Handler를 만들어줍니다. myapp/app.go package myapp import "net/http" // NewHandler make a new myapp handler func NewHandler() http.Handler { mux := http.NewServeMux() return mux } main.go package main import ( "net/http" "./myapp" func main() { http.ListenAndServe(":3000", myapp.NewHandler()) } 이 상태에서 실행시키면 아무것도 뜨지 않는 것을 확인 할 수 있습..

    [바미] Go - File Upload 만들기.

    지난번에 이어서myapp/app_test.go 파일에 테스트 코드를 추가적으로 만들어줍니다. func TestFooHandler_WithoutJson(t *testing.T) { // 1 assert := assert.New(t) res := httptest.NewRecorder() req := httptest.NewRequest("GET", "/foo", nil) mux := NewHttpHandler() mux.ServeHTTP(res, req) assert.Equal(http.StatusOK, res.Code) } 먼저 실패하는 코드를 만들어 줍니다. 1 : GET으로 /foo에 호출하는데 input없이 진행합니다. 그러면 response가 올텐데 StatusOK가 나와야 한다고 하고, 실제 결과를..