您的位置:首页 > 理论基础 > 计算机网络

Golang http 建立Web服务器

2017-10-07 19:42 295 查看
package main

import (
"fmt"
"log"
"net/http"
"strings"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数, 默认是不会解析的
fmt.Println(r.Form) //这些是服务器端的打印信息
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!") //输出到客户端的信息
}

func main() {
http.HandleFunc("/", sayhelloName) //设置访问的路由
err := http.ListenAndServe(":9090", nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

在浏览器中先后输入
http://localhost:9090 http://localhost:9090/?url_long=111&url_long=222
输出到浏览器的内容是: Hello astaxie!

服务器端的控制台的输出:

G:\Users\chenjo>go run web.go

map[]

path /

scheme

[]

map[]

path /favico
4000
n.ico

scheme

[]

map[url_long:[111 222]]

path /

scheme

[111 222]

key: url_long

val: 111222

map[]

path /favicon.ico

scheme

[]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: