Go語言入門經典第18章

gdut17發表於2020-10-17
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

*/

相關文章