go語言實現http服務端與客戶端

go語言的net/http包的使用非常的簡單優雅

(1)服務端

package main

import (
	"flag"
	"fmt"
	"net/http"
)

func main() {
	host := flag.String("host", "127.0.0.1", "listen host")
	port := flag.String("port", "80", "listen port")

	http.HandleFunc("/hello", Hello)

	err := http.ListenAndServe(*host+":"+*port, nil)

	if err != nil {
		panic(err)
	}
}

func Hello(w http.ResponseWriter, req *http.Request) {
<p>	w.Write([]byte("Hello World"))</p>}

http.HandleFunc用來註冊路徑處理函數,會根據給定路徑的不同,調用不同的函數

http.ListenAndSercer監聽iP與端口,本機IP可以省略不寫,僅書寫冒號加端口,如http.ListenAndSercer(“:8080”, nil)

路徑處理函數,參數必須爲w http.ResponseWriter和 req *http.Request且不能有返回值

測試結果:成功


(2)客戶端

package main

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

func main() {
	response, _ := http.Get("http://localhost:80/hello")
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	fmt.Println(string(body))
}

測試結果:成功

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章