Golang网络编程-RESTFUL方法

案例一、极简WEB服务:HelloWeb.go

package main

import (
	"fmt"
	"net/http"
)

func handler(writer http.ResponseWriter, request *http.Request) {
	fmt.Fprintf(writer, "Hello Web, %s!", request.URL.Path[1:])
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":9090", nil)
}

案例二、RESTFUL方法(GET):Get.go

package main

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

func myGet() {
	client := &http.Client{}
	request, err := http.NewRequest("GET", "https://www.baidu.com", nil)
	if err != nil {
		fmt.Println("Error: ", err)
		os.Exit(1)
	}

	respose, err := client.Do(request)
	defer respose.Body.Close()

	cookies := respose.Cookies()
	fmt.Println(cookies)
	if body, err := ioutil.ReadAll(respose.Body); err != nil {
		fmt.Println("Err:", err)
		os.Exit(2)
	} else {
		fmt.Println(string(body))
		//fmt.Println(json.Decoder{})
	}
}

func main() {
	myGet()
}

案例三、RESTFUL方法(GET)返回JSON串:GetPostman.go

package main

import (
	"fmt"
	"io/ioutil"
	//"os"
	//"path/filepath"
	"net/http"
)

func main() {

	url := "https://postman-echo.com/get?foo1=bar1&foo2=bar2"
	method := "GET"

	client := &http.Client {
		//CheckRedirect: func(req *http.Request, via []*http.Request) error {
		//	return http.ErrUseLastResponse
		//},
	}
	req, err := http.NewRequest(method, url, nil)

	if err != nil {
		fmt.Println(err)
	}
	res, err := client.Do(req)
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(string(body))
}

案例四、RESTFUL方法(POST)返回JSON串:PostForm.go

package main

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

func main() {

	url := "https://postman-echo.com/post"
	method := "POST"

	payload := strings.NewReader("foo1=bar1&foo2=bar2")

	client := &http.Client {
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
	}
	res, err := client.Do(req)
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)

	fmt.Println(string(body))
}

案例五、RESTFUL方法(POST)返回JSON串:PostRaw.go

package main

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

func main() {

	url := "https://postman-echo.com/post"
	method := "POST"

	payload := strings.NewReader("This is expected to be sent back as part of response body.")

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
	}
	res, err := client.Do(req)
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)

	fmt.Println(string(body))
}

你可能感兴趣的:(Golang,Go,Golang,RESTFUL)