Go语言入门经典第18章

package main

import (
	"net/http"
	"fmt"
	"io/ioutil"
)

func main() {
	fmt.Println("start")	
	http.HandleFunc("/", hello)
	http.ListenAndServe("0.0.0.0:8000", nil)
}
//curl -is "http://localhost:8000/?foo=1&bar=2"
//curl -is -X POST -d "POSTbody" http://localhost:8000/
//curl -is -X DELETE -d "DELETEss" http://localhost:8000/
func My2(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET" :
		for k,v := range r.URL.Query() {
			fmt.Printf("%s: %s\n", k, v)
		}
		w.Write([]byte("this is GET\n"))
	case "POST" :
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			fmt.Println("post read err")
		}
		fmt.Printf("%s\n", body)
		w.Write([]byte("this is POST\n"))
	case "DELETE":
		w.Write([]byte("this is DELETE\n"))
	}
}

func My(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET" :
		w.Write([]byte("this is GET\n"))
	case "POST" :
		w.Write([]byte("this is POST\n"))
	}
}

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Method)
	w.Header().Set("Qwe", "123")
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	w.Write([]byte("this is body hello\n"))
}

/*

[gdut17@localhost ~]$ curl -is http://localhost:8000
HTTP/1.1 200 OK
Qwe: 123
Date: Sat, 17 Oct 2020 11:52:10 GMT
Content-Length: 19
Content-Type: text/plain; charset=utf-8

this is body hello
[gdut17@localhost ~]$ curl -is -X POST http://localhost:8000
HTTP/1.1 200 OK
Date: Sat, 17 Oct 2020 11:58:09 GMT
Content-Length: 13
Content-Type: text/plain; charset=utf-8

this is POST
[gdut17@localhost ~]$ curl -is -X GET http://localhost:8000
HTTP/1.1 200 OK
Date: Sat, 17 Oct 2020 11:58:16 GMT
Content-Length: 12
Content-Type: text/plain; charset=utf-8

this is GET


[gdut17@localhost ~]$ curl -is "http://localhost:8000/?foo=1&bar=2"
HTTP/1.1 200 OK
Date: Sat, 17 Oct 2020 12:06:20 GMT
Content-Length: 12
Content-Type: text/plain; charset=utf-8

this is GET
[gdut17@localhost ~]$ curl -is -X POST -d "body" http://localhost:8000/
HTTP/1.1 200 OK
Date: Sat, 17 Oct 2020 12:07:38 GMT
Content-Length: 13
Content-Type: text/plain; charset=utf-8

this is POST

[gdut17@localhost ~]$ curl -is -X DELETE -d "DELETEss" http://localhost:8000/
HTTP/1.1 200 OK
Date: Sat, 17 Oct 2020 12:12:47 GMT
Content-Length: 15
Content-Type: text/plain; charset=utf-8

this is DELETE
[gdut17@localhost ~]$ curl -is http://localhost:8000
HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
Qwe: 123
Date: Sat, 17 Oct 2020 12:14:58 GMT
Content-Length: 19

*/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值