갈루아의 반서재

Go 는 net/http 패키지를 통해 HTTP 를지원한다. http 패키지를 사용하여 웹서버를 셋팅해보자. 

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
package main
 
import (
    "fmt"
    "net/http"
    "strings"
    "log"
)
 
func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()  // parse arguments, you have to call this by yourself
    fmt.Println(r.Form)  // print form information in server side
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello astaxie!"// send data to client side
}
 
func main() {
    http.HandleFunc("/", sayhelloName) // set router
    err := http.ListenAndServe(":9090", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
cs

위의 코드를 실행하면, 서버는 9090 포트를 통해 listening 을 하게 된다. 브라우저를 열고 http://localhost:9090 또는 http://***.***.**.**:9090를 타이핑해보자. 아래와 같은 결과를 스크린상에서 확인할 수 있다. 

Hello astaxie 가 스크린상에 나오는 걸 볼 수 있다. 서버측면에서는 이렇게 출력된다.

1
2
3
4
5
6
7
8
9
10
11
12
~/go/src/web# go build
~/go/src/web# ./web
map[]
path /
scheme
[]
map[]
path /favicon.ico
scheme
[]
 
 
cs

여기에 다음과 같은 인수를 넣어서 출력해보자. 

http://***.***.***.**:9090/?url_long=111&url_long=222

1
2
3
4
5
6
map[url_long:[111 222]]
path /
scheme
[111 222]
key: url_long
val: 111222
cs