순수 Go로 만드는 게시판

04. 게시판 첫 화면 정적파일들(CSS)과 함께 띄워봅시당~

지난 시간에 경로별 라우팅 까지 했습니다. 그러면 이제, 정말로 게시판 샘플 화면을 띄워보겠습니다.

오늘은 게시판Main+Css와 리팩토링을 한번 해보도록 하겠습니다.

먼저 /board에 들어갔을 때 게시판 파일을 파싱해서 불러와야겠죠.

1. /board 접속시 html파일 읽어오기

 작업하기전에 이제 폴더구조를 분리를 하려고 합니다. 게시판, 게시글들의 원형이 들어갈 모델폴더와 컨트롤러 폴더,  html파일들이 들어갈 view폴더를 만들어주도록 하겠습니다.

마우스를 우클릭하셔서 폴더를 세개 controller, view, model 을 만들어주세요

(이름은 조금씩 틀려도 상관없습니다 ^^)

자 그러면 controller폴더에 다음과 같은 컨트롤러 파일 BoardController.go 를 만들어주세요.(소스첨부)소스코드는 다음과 같습니다. 

package controller

import (
    "fmt"
	"html/template"
	"net/http"
)

func BoardIndex(w http.ResponseWriter, r *http.Request) {
	fmt.Println("보드에서 인덱스 페이지 접속")
	t, err := template.ParseFiles("view/board/index.html")
	if err != nil {
		panic(err)
	}
	t.Execute(w, nil)
}

자 여기서 11번라인의  template.ParseFiles가 html템플릿을 불러옵니다.

15번라인 :  t.Execute에서 w즉 Writer에 파싱된 파일을 쓰게 되는 것이고 아직 파라미터가 없으므로 두번째 파라미터로 nil을 써주게 됩니다. 그러면...view폴더의 board폴더에 index.html파일이 필요하겠지요?!

view폴더에 board폴더를 만들어 주시고 index.html을 다음과 같이 일단 작성해보도록 하겠습니다 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test</title>
<link rel="stylesheet" href="/public/css/style_board.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div class="container">
		<div id="board">
	<table id="table_board" class="list">
		<colgroup>
			<col width="150">
			<col width="60%">
			<col width="250">
			<col width="100">
			<col width="150">
		</colgroup>
		<thead>
			<tr>
				<th>번호</th>
				<th>제목</th>
				<th>닉네임</th>
				<th>날짜</th>
				<th>조회수</th>
			</tr>
		</thead>
		<tbody>			
				<tr>
					<td colspan="5">
						<p>	
  						게시글이 없습니다.
						</p>
					</td>			
				</tr>
		</tbody>
		<tfoot>
			<tr>
				<td colspan="5">
					<a href="#">글쓰기</a>
				</td>
			</tr>
		</tfoot>
	</table>
</div>
</body>
</html>

자 이렇게 하시면 파싱할 준비도 완료가 되었습니다.

 

이제 main.go 에서 저렇게 바뀐 컨트롤러만 인식시켜주면 됩니다. 다음과 같이 바꿔줘보도록 하겠습니다.

handleBoard메서드를 지우고, 메인함수 내의 파라미터로 컨트롤러 패키지의 BoardIndex로 연결을 해보겠습니다. 다음 사진같이 바꿔주시면 됩니다. 

 controller 패키지가 새로 임포트 되었다는 점 유념해주시구요. HandleFunc에 controller.BoardIndex가 들어가주신 것 봐주시면 됩니다. 중간소스는 생략합니다. 

기존의 Board 첫 화면 띄워주는 메서드를 삭제해주시고 Run을 해주시면 다음과 같은 화면이 뜰 것입니다.

지금의 문제는 CSS같은 정적파일들을 어떻게 연결을 할까. 고민이 되는 것이죠! 

 

2. 정적파일 연결해주기

스프링 프레임워크에서도 DispatcherServlet에서 static 파일들을 따로 관리해주는 방법이 있었습니다.

Go 에서는 비슷한 것이 없나해서 찾아보니! 역시 있었습니다. 다음 소스를 보실까요?

무척 간단합니다. (사실 한줄로도 되는데..아무튼)

fs := http.FileServer(http.Dir("view/static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

view/static 폴더를 파일서버로해서, http.Handle에가 연결해주고 있습니다. 복붙한 소스니 자세한 내용은 생략;;

이 내용을 다음과 같이 작성해주시면 될 것입니다 :) 

func main() {
    fmt.Println("Hello world Board Server")

	fs := http.FileServer(http.Dir("view/static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	r := mux.NewRouter()
	r.HandleFunc("/board/{id}", handleRead)
	r.HandleFunc("/board", controller.BoardIndex)
	r.HandleFunc("/", handler)
	http.Handle("/", r)
	http.ListenAndServe(":8002", nil)
}

 

static으로 시작하는 것들은 view/static으로 연결한다 정도로 알아둡시다(무책임)

자 그럼 static 폴더에 다음과 같은 구조로 css파일을 줘보도록 하겠습니다.

view/static/css  폴더(없으면 생성해주시고) 그 안에 제가 제공해드리는  style_board.css 파일을 넣어줍니다.

css 주소 : https://github.com/arahansa/go_pureboard/blob/master/view/static/css/style_board.css

그러면 다음과 같은 이쁜 게시판 메인화면이 나옵니다^^; (아직 반응형은 아닙니다 ㅠ)

다음번에는 이제 database처리로 시작이 되겠네요.  게시글이 없단 것을 봐야할것같습니다. 그럼 오늘은 이만^^;

 

댓글

댓글 본문
  1. 풀스택을 향해
    어려운 것을 알게 되실 겁니다....
    대화보기
    • ㅁㅊ ㅋㅋ
      GO언어로 웹개발하기 진짜 쉽고 재밌네요 ㅋㅋ 대박
    • 꼬반
      오타 수정 건의 합니다. index.html 에 보면

      <link rel="stylesheet" href="/public/css/style_board.css" type="text/css" />

      으로 되어 있는데요

      <link rel="stylesheet" href="/static/css/style_board.css" type="text/css" />

      으로 수정되어야 합니다.
    버전 관리
    아라한사
    현재 버전
    선택 버전
    graphittie 자세히 보기