[Go] Go 라이브러리를 사용해 HTML 띄우기

1. Go 웹 서버 설정

Go 언어로 웹 개발을 하기위해서 기본적인 레이아웃을 만드는 방법은 HTML 템플릿과 Go http를 사용하면 됩니다. 먼저 Go를 사용해서 웹 서버를 설정해줍니다.

package main

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

type PageVariables struct {
	Title string
}

func main() {
	// 정적 파일을 사용하기 위한 핸들러 설정
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	
	http.HandleFunc("/", HomePage)
	http.ListenAndServe(":8080", nil);
}

func HomePage(w http.ResponseWriter, r *http.Request) {
	PageVariables := PageVariables{
		Title: "My WebSite",
	}
	tmpl, err := template.ParseFiles("templates/layout.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return 
	}
	tmpl.Execute(w, PageVariables)
}

2. HTML 템플릿 만들기

template 폴더를 만들어 그 안에 layout.html 파일을 생성해서 아래 Header를 포함한 기본 레이아웃을 작성해줍니다.

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{ .Title }}</title>
    <link rel="stylesheet" href="/static/style.css" />
    <!-- CSS 파일 불러오기 -->
  </head>

  <body>
    <div class="body-container">
      <header>
        <h1>{{ .Title }}</h1>
        <nav class="nav-container">
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
            <li><a href="/contact">Contact</a></li>
          </ul>
        </nav>
      </header>
      <main>
        <!-- Content will be injected here -->
        <p>여기에 콘텐츠가 들어갑니다.</p>
      </main>
      <footer>
        <p>&copy; 2023 My Blog. All rights reserved.</p>
      </footer>
    </div>
  </body>
</html>
* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
  overflow-x: hidden;
}

body,
html {
  width: 100%;
  height: 100%;
}

.body-container {
  width: 100%;
  max-width: 1300px;
  border: 1px solid red;
  text-align: center;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

main {
  flex: 1;
}

footer {
  background-color: #4caf50;
  color: white;
  padding: 10px;
}

.nav-container ul {
  display: flex;
  text-align: center;
  justify-content: center;
}
.nav-container ul li {
  margin: 20px;
}

 

이제 아래 명령어로 Go 서버를 실행합니다. 

go run main.go

 

웹 브라우저에 http://localhost:8080에 접속하면, 작성한 HTML과 CSS 스타일일 적용된 페이지를 확인할 수 있습니다.

  • 정적 파일 서빙: http.FileServer를 사용하여 CSS 파일과 같은 정적 파일 서빙
  • HTML 템플릿: <link> 태그를 사용해 CSS 파일을 HTML에 포함

이렇게 Go 웹 애플리케이션에 CSS 스타일 파일을 불러오고, 레이아웃을 적용할 수 있습니다.


 

 

GitHub - Koras02/go-http-layout

Contribute to Koras02/go-http-layout development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Go' 카테고리의 다른 글

[Go] 8장(완) 고루틴과 채널  (1) 2025.03.04
[Go] 7장 구조체와 인터페이스  (0) 2025.03.04
[Go] 6장 맵  (0) 2025.03.03
[GO] 5장 배열과 슬라이스  (0) 2025.02.28
[Go] 4장 함수(Function)  (0) 2025.02.26