테스트 사이트 - 개발 중인 베타 버전입니다

Echo 웹 프레임워크에서 헤더 작성하는 방법

· 5년 전 · 2855

헤매다가 방법을 발견해서 씁니다.

 

일단은 2가지가 있습니다.

 

1가지는 전체 페이지에 헤더를 주는 법.

 

func HeaderSet(next echo.HandlerFunc) echo.HandlerFunc {
   return func(c echo.Context) error {
      c.Response().Header().Set("Expires", "0")
      c.Response().Header().Set(echo.HeaderLastModified, time.Now().Format("Mon, 02 Dec 2019 09:56:15 GMT")) // Mon, 02 Dec 2019 09:56:15 GMT
      c.Response().Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")
      c.Response().Header().Set("Cache-Control", "pre-check=0, post-check=0, max-age=0")
      c.Response().Header().Set("Pragma", "no-cache")
      c.Response().Header().Set(echo.HeaderContentType, "text/html; charset=utf-8")
      c.Response().Header().Set("X-Robots-Tag", "noindex")

      return next(c)
   }
}

라는 함수를 작성 후

e := echo.New()
e.Use(HeaderSet)

로 미들웨어를 추가하여 쓸 수 있습니다.

 

만약 e.Use 를 사용하여 헤더를 작성했을 경우

전체 페이지에 해당 헤더가 추가됩니다.

 

2번째 방법으로는 각 HTTP Request (맞는지 모르겠네요)에 헤더를 따로 추가하는 방법입니다.

 

e.POST("/install/1", InstallProcess) // 인스톨 프로세스

라고 했다면 InstallProcess 는 핸들러 함수가 됩니다.

 

func InstallProcess(c echo.Context) error {
   c.Response().Header().Set("Expires", "0")
   c.Response().Header().Set(echo.HeaderLastModified, time.Now().Format("Mon, 02 Dec 2019 09:56:15 GMT")) // Mon, 02 Dec 2019 09:56:15 GMT
   c.Response().Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")
   c.Response().Header().Set("Cache-Control", "pre-check=0, post-check=0, max-age=0")
   c.Response().Header().Set("Pragma", "no-cache")
   c.Response().Header().Set(echo.HeaderContentType, "text/html; charset=utf-8")
   c.Response().Header().Set("X-Robots-Tag", "noindex")
   c.Response().WriteHeader(http.StatusOK)

 

이 핸들러 함수에

c.Response().Header().Set(키, 값)

c.Response().WriteHeader(HTTP 상태 코드 값)

을 넣어준다면 각 HTTP Request 마다 헤더를 따로 작성할 수 있습니다.

 

이거때문에 다 갈아엎을까 생각하다가 겨우 찾았네요 ㅎㅎ

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
92
82
80
79
78
77
76
75
72
65
64
63
62
57
55
54
53
52
51
50
46
44
43
39
34
29
28
27
26
22