티스토리 뷰

Study/Go Lang

[Go Lang] Web Server?

Hoon's Blog 2019. 12. 18. 17:53

# Web Server?

 

- Go의 표준 패키지인 net/http 패키지는 웹 관련 서버 기능을 제공함. 

 

import (
    "net/http"
)

 


 

- 간단한 예제

 

// HttpExam project main.go
package main

import (
	"net/http"
)

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

 


 

http://localhost:5000/hello

더보기

HandleFunc()의 /hello Path에 대한 익명함수를 실행하여 Hello World를 실행함.

 

익명함수 내의 

  http.ResponseWrite 파라미터는 HTTP Response에 무언가를 쓸수있게 함.

  http.Request 파라미터는 입력된 Request 요청을 검토할 수 있게 함(?)

 

http.ListenAndServe () 메서드는 2개의 파라미터를 가지며 

  1. 포트 지정 

  2. 어떤 ServeMux를 사용할 지를 지정함. (관련된 내용은 추후에 보충)

 


 

- http.Handler 인터페이스를 갖는 testHandler 라는 struct를 정의하고 이 struct의 메서드 ServeHTTP()을 구현한 예

 

// HttpExam project main.go
package main

import (
	"net/http"
)

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

	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://localhost:5000/

 


# 참고

- http://golang.site/go/article/111-%EA%B0%84%EB%8B%A8%ED%95%9C-%EC%9B%B9-%EC%84%9C%EB%B2%84-HTTP-%EC%84%9C%EB%B2%84

 

예제로 배우는 Go 프로그래밍 - 간단한 웹 서버 (HTTP 서버)

1. 간단한 HTTP 서버 Go의 표준 패키지인 net/http 패키지는 웹 관련 서버 (및 클라이언트) 기능을 제공한다. Go에서 HTTP 서버를 만들기 위해 중요한 http 패키지 메서드로 ListenAndServe(), Handle(), HandleFunc() 등을 들 수 있다. ListenAndServe() 메서드는 지정된 포트에 웹 서버를 열고 클라이언트 Request를 받아들여 새 Go 루틴에 작업을 할당하는 일을 한다. Handle()과 Ha

golang.site

 

'Study > Go Lang' 카테고리의 다른 글

[Go Lang] Mahalanobis Distance  (0) 2019.12.18
[Go Lang] Euclidean Distance  (0) 2019.12.18
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함