라우팅 설정에서는 go의 외부라이브러리인 mux를 사용해보도록 하겠습니다.
깃헙주소는 다음과 같습니다 : https://github.com/gorilla/mux
그리고 터미널환경에서 go get github.com/gorilla/mux 를 해주셔야 합니다.
그후로 소스를 적을 것입니다.
1. 먼저 /board로 연결하고 싶습니다! 정적 라우팅
자, 가장 먼저 첫걸음으로 /board로 연결해봅시다.
먼저 소스를 다음과 같이 적어줘봅시다.
package main
import (
"fmt"
"net/http"
)
func main() {
fmt.Println("Hello world Board Server")
http.HandleFunc("/board", handleBoard)
http.HandleFunc("/", handler)
http.ListenAndServe(":8001", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello I will be a Board. %s", r.URL.Path[1:])
}
func handleBoard(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello I am Board. %s", r.URL.Path[1:])
}
뭔가 살짝 바뀐 것같은 느낌이 오시나요?
http.HandleFunc("/board", handleBoard)
가 main 함수에 추가되었고, handleBoard를 처리할
func handleBoard(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello I am Board. %s", r.URL.Path[1:])
}
가 추가되었습니다.
포트번호가 잠깐 바뀐 것은 애교로 봐주세요;; ㅎ;
자, 그러면! /board/id 로도 접속 하고 싶다는 생각이 들 것입니다!!
2. /board/글번호 로 접속하고 싶은데요? 동적 라우팅
여기서부터 mux를 쓰게 됩니다 :)
mux의 매뉴얼을 참고하여서 대략 이런 형태로 서버경로를 설정합니다.
r := mux.NewRouter()
r.HandleFunc("/board/{id}", 메서드)
r.HandleFunc("/board", 메서드)
r.HandleFunc("/", 메서드)
http.Handle("/", r)
그리고 id값을 추출할때는 http.Request 요청에서 다음과 같이 추출하게 됩니다.
나중에는 여기서 얻는 값을 가지고 체크를 하거나, 데이터베이스에 해당 글 번호를 불러오는 데 사용되겠죠!
vars := mux.Vars(r) Id := vars["id"]
어디 한번 전체적인 소스로 볼까요?(임포트를 잊지 말아주세요 :)
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
fmt.Println("Hello world Board Server")
r := mux.NewRouter()
r.HandleFunc("/board/{id}", handleRead)
r.HandleFunc("/board", handleBoard)
r.HandleFunc("/", handler)
http.Handle("/", r)
http.ListenAndServe(":8002", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello I will be a Board. %s", r.URL.Path[1:])
}
func handleBoard(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello I am Board. %s", r.URL.Path[1:])
}
func handleRead(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
Id := vars["id"]
fmt.Println("id값은 ,", Id)
fmt.Fprintf(w, "Hello I am Board. 게시글 넘버 : %s", Id)
}


자 , 그러면 다음 시간에는 이걸 좀 더 폴더별로 리팩토링해보고,
외부파일을 불러오는 것까지 한번 해보겠습니다. ㅎㅎ


