搭建最简单的web服务器,在浏览器输入 localhost:9002/baby
会打印出 Hi, I love you baby
package main
import (
"fmt"
"net/http"
"strings"
"html"
"io/ioutil"
//"encoding/json"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Servers []Server
ServersID string
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":9002", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
fmt.Fprintf(w, "Hi, I love you %s", html.EscapeString(r.URL.Path[1:]))
if r.Method == "GET" {
fmt.Println("method:", r.Method) //获取请求的方法
fmt.Println("username", r.Form["username"])
fmt.Println("password", r.Form["password"])
for k, v := range r.Form {
fmt.Print("key:", k, "; ")
fmt.Println("val:", strings.Join(v, ""))
}
} else if r.Method == "POST" {
result, _:= ioutil.ReadAll(r.Body)
r.Body.Close()
fmt.Printf("%s\n", result)
}
}
有疑问加站长微信联系(非本文作者)