go 實現簡單的http web服務

package main

import (
	"fmt"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Println("handle hello")
	fmt.Fprintf(w, "hello12345")
}

func index (w http.ResponseWriter, r *http.Request) {
	//Fprintf根據format參數生成格式化的字符串並寫入w。返回寫入的字節數和遇到的任何錯誤
	fmt.Fprintf(w, "this is index")
}

func main () {
	//HandleFunc註冊一個處理器函數handler和對應的模式pattern
	//實現路由功能, hello 爲函數名
	http.HandleFunc("/", hello)
	http.HandleFunc("/index", index)
	//ListenAndServe監聽srv.Addr指定的TCP地址,而且會調用Serve方法接收到的鏈接。若是srv.Addr爲空字符串,會使用":http"。
	err := http.ListenAndServe("0.0.0.0:8080", nil)

	if err != nil {
		fmt.Println("http listen failed")
	}

}

  2.客戶端函數

  

//http 客戶端
package main

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

func main () {
	res, err := http.Get("http://www.baidu.com")
	if err != nil {
		fmt.Println("get faield,error:,", err)
		return 
	}

	data, err := ioutil.ReadAll(res.Body)

	if err != nil {
		fmt.Println("read err, error:,", err)
		return
	}

	fmt.Println(string(data))
}

  3. head請求this

  

//head請求實例子
package main

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

var url = []string{
	"http://www.baidu.com",
	"http://www.gegole.com",
	"http://www.taobao.com",
}

func main () {
	for _, v := range url {
		//本身創建客戶端
		client := http.Client{
			Transport: &http.Transport {
				Dial: func(network, addr string) (net.Conn, error) {
					//設置超時時間
					timeout := 2 * time.Second
					return net.DialTimeout(network, addr, timeout)
				}, 
			},
		}

		resp, err := client.Head(v)

		if err != nil {
			fmt.Println("send head failed, error:", err)
			continue
		}

		fmt.Printf("head succ, status: %v \n", resp.Status)

	}
}
相關文章
相關標籤/搜索