go语言简单的处理http请求的函数实例,http请求处理类

go语言简单的处理http请求的函数实例,http请求处理类。本文实例汇报了go语言简单的管理http须求的函数。分享给我们供大家仿效。具体落实情势如下:

func someHandler(w http.ResponseWriter, r *http.Request) {
    // read form value
    value := r.FormValue("value")
    if r.Method == "POST" {
        // receive posted data
        body, err := ioutil.ReadAll(r.Body)

}

func main() {
    http.HandleFunc("/", someHandler)
    http.ListenAndServe(":8080", nil)
}

以下是net/http包中的集中举行http须要的方法:

复制代码 代码如下:

[PHP]代码

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

// http.Get
func httpGet() {
    resp, err := http.Get("http://www.baidu.com")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

func httpPost() {
    resp, err := http.Post("http://www.baidu.com",
                           "application/x-www-form-urlencode",
                           strings.NewReader("name=abc")) // Content-Type post请求必须设置
    if err != nil {
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

// http.Clien
func httpDo() {
    client := &http.Client{}
    req, err := http.NewRequest("POST", 
                                "http://www.baidu.com", 
                                strings.NewReader("name=abc"))
    if err != nil {
        return
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    resp, err := client.Do(req)
    if err != nil {
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return
    }
    fmt.Println(string(body))
}

相关文章