[Go] Go Web Programming Basic 02 - Install Gorilla
Install Gorilla For Web Server
지난번에는 http 모듈을 이용하여 웹 서버를 구현했지만 웹 서버를 편하게 개발하기에는 그리 좋은 모듈은 아니다.
이번에는 Gorilla 를 이용한 웹 서버를 만들어 볼 것이다.
Install Gorilla
Gorilla 를 설치하기 위해서 다음 명령을 콘솔에서 실행하자.
go get github.com/gorilla/mux
go 에서는 go get
을 이용하면 필요한 모듈을 설치할 수 있다.
main.go 수정하기.
이제는 Gorilla를 이용하여 동일한 기능으로 웹 서버를 만들어 보자.
import (
"fmt"
"html"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HelloWorld)
r.HandleFunc("/path/value", ResponsePath)
http.Handle("/", r)
fmt.Println("Server start on port: ", 8080)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func HelloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World")
}
func ResponsePath(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Your request path is :%q", html.EscapeString(r.URL.Path))
}
사실 크게 달라진 부분은 없다.
- mux.NewRouter: request 경로를 분석하고, 해당하는 핸들러로 라우팅 한다.
- r.HandleFunc: 라우터에대해서 핸들링을 수행할 경로와 경로에 대해서 동작할 핸들러를 지정해준다.
테스트하기
간단하게 다음과 같이 테스트를 수행해 보자.
go run main.go
✗ curl http://localhost:8080/
Hello, World
curl http://localhost:8080/path/value
Your request path is :"/path/value"
http 모듈을 이용했을 때와 같이 동일한 결과를 확인할 수 있다.
Wrap Up
Gorilla 를 이용하여 정말 간단한 웹 서버를 만들어 보았다.
만들어진 내용은 http 모듈을 이용했을때와 동일한 처리를 수행하며, 코드 역시 크게 변경된 것은 없다.
하지만 다음부터 알아볼 내용들을 보면 좀더 강력한 기능들이 존재함을 이해할 수 있을 것이다.
관련 Git 에서 소스코드를 확인 가능