티스토리 뷰

Go를 이용하여 아주 간단하게 루트(/)를 요청하면 응답이 갈 수 하는 코드 입니다.

go-wrapper를 이용하여 구동만 시켜 주면 바로 서버가 됩니다.

 

1. HandleFunc 이용하기

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("Hello World"))
    })

    http.ListenAndServe(":5000", nil)
}

 

2. http.Handle() 이용

package main
 
import (
    "net/http"
)
 
func main() {
    http.Handle("/", new(testHandler))
 
    http.ListenAndServe(":5000", nil)
}
 
type testHandler struct {
    http.Handler
}
 
func (h *testHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    str := "Your Request Path is " + req.URL.Path
    w.Write([]byte(str))
}

http.Handle()을 이용하는 방법으로 / 패스로 들어오는 값 자체를 핸들하게 만들수 있게 됩니다.

위에서 보여준 부분에서는 testHandler를 받아들여서 Your Request Path is ... 이렇게 나오도록 하였습니다.

 

3. 간단한 Static 파일 핸들러

일반적인 API 서버가 아닐 경우에 Content-Type등을 지정하여 주어야 할 경우에 대한 부분입니다.

package main
 
import (
    "io/ioutil"
    "net/http"
    "path/filepath"
)
 
func main() {
    http.Handle("/", new(staticHandler))
 
    http.ListenAndServe(":5000", nil)
}
 
type staticHandler struct {
    http.Handler
}
 
func (h *staticHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    localPath := "wwwroot" + req.URL.Path
    content, err := ioutil.ReadFile(localPath)
    if err != nil {
        w.WriteHeader(404)
        w.Write([]byte(http.StatusText(404)))
        return
    }
 
    contentType := getContentType(localPath)
    w.Header().Add("Content-Type", contentType)
    w.Write(content)
}
 
func getContentType(localPath string) string {
    var contentType string
    ext := filepath.Ext(localPath)
 
    switch ext {
    case ".html":
        contentType = "text/html"
    case ".css":
        contentType = "text/css"
    case ".js":
        contentType = "application/javascript"
    case ".png":
        contentType = "image/png"
    case ".jpg":
        contentType = "image/jpeg"
    default:
        contentType = "text/plain"
    }
 
    return contentType
}

각 파일들 마다 content-type을 지정하여 리턴할 수 있도록 개발되어 있습니다.

 

4. http.FileServer를 이용한 Static 파일 서버

정적 파일들을 웹서버에서 클라이언트로 그대로 전달하기 위해 내장된 기능인 http.FileServer를 사용 할 수 있다고 합니다. 세밀하게 어떠한 부분들을 조정하여 파일의 내용을 전달 할 수는 없지만 간단하게 만들기에는 좋은것이라 합니다.

package main
 
import (
    "net/http"
)
 
func main() {   
    http.Handle("/", http.FileServer(http.Dir("wwwroot")))
    //http.Handle("/static", http.FileServer(http.Dir("wwwroot")))
    http.ListenAndServe(":5000", nil)
}

'Language > Go' 카테고리의 다른 글

Write in go  (0) 2020.07.02
Go. slice에 insert 구현하기  (0) 2020.06.21
Go. 99Class  (0) 2019.09.16
Go. const와 iota  (0) 2019.09.09
Golang debug error가 Visual Studio Code에서 발생할때... 다른곳에서 날수도 있음.  (0) 2019.08.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함