golang 搭建简单web服务器

来源:互联网 发布:mac口红代理价格表 编辑:程序博客网 时间:2024/05/16 16:04

搭建最简单的web服务器,在浏览器输入 localhost:9002/baby
会打印出 Hi, I love you baby

package mainimport (  "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)  } }
0 0
原创粉丝点击