Web Tutorial With Golang

Published 08-12-2019 20:23:52

[Intro]

최근 토이프로젝트를 위한 웹 크롤러를 만들기 시작했다. 사실 익숙한 python과 Beautiful Soup 활용하여 빠르게 진행해도 되지만, Golang에 대한 호기심으로 방향을 바꿨다. 하루정도 Tutorial 보면서 접한 Golang의 이미지는 컴파일러 언어답게 상당히 빠르고 간결하며, 여타 프레임워크 없이도 빠르게 배포할 수 있다는 장점이 있는듯 하다.

대형 프로젝트에서는 API서버 위주로 사용할 것이라 생각이 들지만, 간단한 웹페이지는 정말 놀라울 정도로 직관적이게 생성할 수 있다. REST!!

#

[Environment]

개발 환경은 몇년째 유지중인 CentOS(개발은 역시 리눅스+빔이지!)와 단지 Golang이며, Github Repository에서 작업진행 상황을 확인할 수 있다.

#

[Web With Golang?]

튜토리얼을 진행하고, 프로젝트 디렉토리를 다음과 같이 생성했다.

/
+--static/
    +--css/
    +--images/
    +--js/
    +--page/
        +--{view}.html
    +--index.html
+--crawler.go

프로젝트 구조를 보면 현재 코드는.. 단 하나뿐이다! 와우!

단순히 구조를 설명하면

(1) 뷰페이지 선언 crawler.go - static/{view}.html

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page){
    t, err := template.ParseFiles("static/" + tmpl +".html")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    err = t.Execute(w, p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
} 

(2) 라우팅 상세 설정 crawler.go

func getCrawlUrlHandler(w http.ResponseWriter, r *http.Request){
    body := r.FormValue("body")
    p := &Page{Title: title, Body: []byte(body)}
    renderTemplate(w, "page/getUrl", p)
}

post데이터는 FormValue(“body”)로 받으면 된다.

(3) 라우팅 설정 crawler.go - 8080포트로 서비스

func main(){
    http.HandleFunc("/getUrl", getCrawlUrlHandler)
    log.Fatal(http.ListenAndServe(":8080"), nil)
}

..끝이다! 야호!

(4) 렌더링 페이지 e.g.) /static/getUrl.html

<body>
<div class="container">
<form action="/back_run" method="POST">
<div>
<textarea name="body">{{printf "%s" .Body}}</textarea>
</div>
<div>
<input type="submit" value="submit">
</div>
</form>
</div>
</body>

submit된 데이터는 /back_run 라우팅으로 전달되며, 위 라우팅 상세 설정에 새로운 func를 선언하여 값을 받고, 내부적인 처리를 진행하면된다. 이후, 같은 func에서 렌더링까지 처리할 수 있으니..!