더북(TheBook)

app 폴더에 main.go 파일을 생성하고 다음과 같이 코드를 작성한다.

▼ main.go

package main
 
import (
    "net/http"
     
    "github.com/codegangsta/negroni"
    "github.com/julienschmidt/httprouter"
    "github.com/unrolled/render"
)
 
var renderer     *render.Render
 
func init() {
    // 렌더러 생성
    renderer = render.New()
}
 
func main() {
    // 라우터 생성
    router := httprouter.New()
     
    // 핸들러 정의
    router.GET("/", func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
        // 렌더러를 사용하여 템플릿 렌더링
        renderer.HTML(w, http.StatusOK, "index", map[string]string{"title": "Simple Chat!"})
    })
     
    // negroni 미들웨어 생성
    n := negroni.Classic()
     
    // negroni에 router를 핸들러로 등록
    n.UseHandler(router)
     
    // 웹 서버 실행
    n.Run(":3000")
}

▼ templates/index.tmpl

<html>
    <body>
        <h1>{{ .title }}</h1>
    </body>
</html>

명령 프롬프트에서 main.go 파일을 실행하여 웹 서버가 동작하는지 확인해 보자.

명령 프롬프트

$ go run main.go

[negroni] listening on :3000

[negroni] Started GET /

[negroni] Completed 200 OK in 288.035?s

브라우저로 http://localhost:3000에 접속해 보면 Simple Chat! 메시지를 볼 수 있다.

그림 9-5 Simple Chat! 메시지 출력
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.