프로그래밍(Web)/Golang

    [바미] Go - OAuth 2.0

    OAuth? 자체 회원가입을 가지지 않고(또는 있음에도), 외부 유명한 사이트(구글, 페이스북, 등등)를 통해 계정의 정보를 가져오는것을 말합니다. 이것이 동작하는 구조는 클라이언트가 웹 사이트(A)에 로그인 요청을 하고, 그 사이트가 요청을 받으면 구글이나 페이스북 등에 OAuth를 요청하고, 그러면 클라이언트에게 해당 사이트(구글, 페이스북 등)의 로그인화면을 알려주게 되고, 클라이언트가 그 화면에서 로그인을 하고, 완료가 되면 콜백주소를 등록하게 되고, 그 해당 사이트(구글, 페이스북 등)가 클라이언트가 원래 로그인 하려고 했었던 사이트(A)에 콜백 주소를 통해 Refresh Key와 API Key를 알려주게 됩니다. 그리고 그 API Key를 통해 회원의 정보를 인가받게 됩니다. 근데 이 Key는..

    [바미] 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()) } 이 상태에서 실행시키면 아무것도 뜨지 않는 것을 확인 할 수 있습..