ListenAndServer 는 addr 주소로 TCP 네트워크로 listens 하게 됩니다.
그리고 Handler 로 서비스를 호출하여 들어오는 연결에 대한 요청을 처리합니다.
handler 는 일반적으로 nil 이고 이 경우 DefaultServeMux가 사용됩니다.
package main
import (
"fmt"
"net/http"
)
const port string = ":4000"
func main() {
fmt.Printf("Listening server : http://localhost%s\n", port)
http.ListenAndServe(port, nil)
}
localhost:4000 에 접속하면 404 page not found 가 나타나므로 정상 작동 하는 것을 알 수 있다.
handleFunc 는 주어진 pattern에 대한 handler function을 DefaultServeMux 에 등록 합니다.
라우팅 역할을 한다고 생각하면 된다.
매개 변수로는 pattern 과 handler를 받게 되는데 pattern 에는 라우팅 할 주소를 적어주면 되고 handler 함수는
func(rw http.ResponseWriter, r *http.Request)
이 구조에 맞게 작성해서 등록해주면 된다.
package main
import (
"fmt"
"net/http"
)
const port string = ":4000"
func main() {
fmt.Printf("Listening server : http://localhost%s\n", port)
http.HandleFunc("/" ,func(rw http.ResponseWriter, r *http.Request) {
fmt.Fprint(rw, "Hello World!")
})
http.ListenAndServe(port, nil)
}
"/" 로 라우팅 하면 Hello World 가 나타나게 하는 예제이다.
HandleFunc 에 "/" 패턴을 등록하고 Fprint 로 io를 http Response 로 바꾸고 "hello world" 문자열을 출력하게 된다.
template 패키지를 사용하면 쉽게 html 템플릿을 가져와서 SSR 방식으로 렌더링 할 수 있다.
vscode 에서 확장자를 .gohtml 을 사용하고 gotemplate-syntax 확장자를 사용하면 나중에 data 를 전달 할때 하이라이팅이 표시 되므로 미리 다운 받는다.
Template 패키지의 ParseFiles 메서드로 해당 파일을 파싱해서 가져온다.
ParseFiles 메서드는 매개변수로는 템플릿 파일네임을 받고*template.Template, error 을 리턴해준다
package main
import (
"fmt"
"html/template"
"net/http"
)
const port string = ":4000"
func HandleHome(rw http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("home.gohtml")
if err != nil {
panic(err)
}
}
func main() {
fmt.Printf("Listening server : http://localhost%s\n", port)
http.HandleFunc("/" , HandleHome)
http.ListenAndServe(port, nil)
}
Execute 메서드로 파싱한 템플릿을 렌더링 해주게 된다.
매개변수로는 입출력 변수와 데이터 인터페이스를 받게 된다.
package main
import (
"fmt"
"html/template"
"net/http"
)
const port string = ":4000"
func HandleHome(rw http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("home.gohtml")
if err != nil {
panic(err)
}
tmpl.Execute(rw, nil)
}
func main() {
fmt.Printf("Listening server : http://localhost%s\n", port)
http.HandleFunc("/" , HandleHome)
http.ListenAndServe(port, nil)
}
성공적으로 렌더링 하게 된다.
template 패키지는 Must 라는 유틸리티를 제공해 주는데 이는 에러처리를 간편하게 할 수 있게 도와준다.
매개변수로 (*template.Template, err) 를 받고
에러가 있을 경우 에러 핸들링을 해주고 에러가 없으면 정상적인 *template.Template 값을 반환 해 준다.
아래 코드는 위에 예제와 100% 일치하는 결과를 내놓는다.
package main
import (
"fmt"
"html/template"
"net/http"
)
const port string = ":4000"
func HandleHome(rw http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("home.gohtml"))
tmpl.Execute(rw, nil)
}
func main() {
fmt.Printf("Listening server : http://localhost%s\n", port)
http.HandleFunc("/" , HandleHome)
http.ListenAndServe(port, nil)
}