---
title: "用Golang的 http 包建立 Web 服务器"
author: "kanglecjr"
date: "2014-12-30T00:07:18Z"
tags: []
categories: ["编程语言"]
slug: "golang-http-web"
draft: false
lastmod: "2014-12-30T00:09:46Z"
id: 2171061
url: "https://kanglecjr.iteye.com/blog/2171061"
---

http 包建立 Web 服务器

```
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&gt;go run web.go

map\[]

path /

scheme

\[]

map\[]

path /favicon.ico

scheme

\[]

map\[url\_long:\[111 222]]

path /

scheme

\[111 222]

key: url\_long

val: 111222

map\[]

path /favicon.ico

scheme

\[]