//包體引入
import "net/http"
func main() {
url := "http://www.baidu.com"
resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
body , err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(len(string(body)))
}
func main() {
body := "{\"title\":\"xxxx\"}"
response, err := http.Post("xxxx", "application/json",bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("net http post method err ,", err)
}
defer response.Body.Close()
rlt, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(rlt))
}
func main() {
resp, err := http.PostForm("https://accounts.douban.com/j/mobile/login/basic",url.Values{"name": {"zhangsan@xx.com"}, "password": {"12356"}})
fmt.Println(resp.Request.URL)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(body))
}
//NewRequest 使用給定的Method,URL 和可選的BODY參數(shù),返回一個(gè)新的Request,適用于使用Client.Do或者Transport.RoundTrip。 如果method參數(shù)為空字符串,默認(rèn)使用Get方法。
func main() {
client := &http.Client{
Timeout:3 * time.Second,
}
req, err := http.NewRequest("GET","http://www.baidu.com",nil )
req.Header.Add("X-Requested-With", "XMLHttpRequest")
if err != nil {
fmt.Println(err)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(body))
}
//單路由服務(wù)
func main() {
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world...")
}))
http.ListenAndServe(":8080", nil)
}
//多路復(fù)用 ServeMux,可以配置多條路由規(guī)則
//不要忘記將mux 注冊(cè)到http里面
type apiHandler struct{}
func (apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request){
w.Write([]byte("hello world"))
}
func main() {
mux := http.NewServeMux()
mux.Handle("/",apiHandler{})//只要實(shí)現(xiàn)了Handler接口就可以
mux.Handle("/hello",http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){
fmt.Fprint(w,"hello, boy...")
}))
http.ListenAndServe(":8080",mux )
}
//方式一
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome...")
})
server := http.Server{
Addr: ":8080",
Handler: mux,
}
server.ListenAndServe()
}
//方式二
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome...")
})
http.ListenAndServe(":8080",mux)
}