发送一个简单的GET请求

package main

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

func main() {
    client := &http.Client{}

    // 地址为api.imjad.cn的一言接口,执行后可以收到一言数据
    res, err := client.Get("https://api.imjad.cn/hitokoto/")

    if err != nil {
        fmt.Println(err)
        return
    }

    result, err := ioutil.ReadAll(res.Body)
    defer res.Body.Close()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s", result)
}

发送一个简单的POST请求

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // 配置需要发送的值
    type Data struct {
        Page  int `json: "page"`
        Count int `json: "count"`
    }

    data := Data{
        Page:  1,
        Count: 5,
    }

    params, err := json.Marshal(data)
    //string(params): {"page":"xx@xx.com","count":"123456"}

    client := &http.Client{}

    // 地址为api.apiopen.top的网易新闻接口
    res, err := client.Post("https://api.apiopen.top/getWangYiNews", "application/json", bytes.NewBuffer(params))

    if err != nil {
        fmt.Println(err)
        return
    }

    result, err := ioutil.ReadAll(res.Body)
    defer res.Body.Close()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s", result)
}

发送复杂请求

以下例子均搭配Go service示例

使用GET发送带参数请求

// client
package main

import (
    "crypto/tls"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

func main() {
    // 配置需要发送的值
    params := url.Values{
        "email":    {"xx@xx.com"},
        "password": {"123456"},
    }

    req, err := http.NewRequest("GET", "https://localhost:9090/login", nil)

    req.URL.RawQuery = params.Encode()

    if err != nil {
        fmt.Println(err)
        return
    }

    // 因下例service使用的ssl证书为不受信任的,故这里需要配置Go client不验证证书是否有效
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }

    client := &http.Client{
        Transport: tr,
    }

    resp, err := client.Do(req)

    if err != nil {
        fmt.Println(err)
        return
    }

    result, err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s", result)
}
// service
package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
)

func index(w http.ResponseWriter, r *http.Request) {
    if r.RequestURI != "/" {
        w.WriteHeader(404)
        return
    }
    fmt.Fprintf(w, "%s\n", "Hello Wrold!")
    fmt.Fprintf(w, "You are in the index\n")
}

func login(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    if len(r.Form) > 0 {
        for k, v := range r.Form {
            fmt.Printf("%s=%s\n", k, v[0])
        }
    }
    fmt.Fprintf(w, "You are in the login\n")
}

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/", index)
    mux.HandleFunc("/login", login)

    cert, err := tls.LoadX509KeyPair("./server.pem", "./server.key")
    if err != nil {
        fmt.Println(err)
        return
    }

    server := &http.Server{
        Addr:    "0.0.0.0:9090",
        Handler: mux,
        TLSConfig: &tls.Config{
            Certificates: []tls.Certificate{cert},
        },
    }

    server.ListenAndServeTLS("", "")
}

使用POST发送带参数且Content-Type为application/x-www-form-urlencoded的请求

// client
package main

import (
    "crypto/tls"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
)

func main(){
    // 配置需要发送的值
    params := url.Values{
        "email":    {"xx@xx.com"},
        "password": {"123456"},
    }

    req, err := http.NewRequest("POST", "https://localhost:9090/login", strings.NewReader(params.Encode()))

    if err != nil {
        fmt.Println(err)
        return
    }

    // 添加header
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    // 因下例service使用的ssl证书为不受信任的,故这里需要配置Go client不验证证书是否有效
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }

    client := &http.Client{
        Transport: tr,
    }

    resp, err := client.Do(req)

    if err != nil {
        fmt.Println(err)
        return
    }

    result, err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s", result)
}
// service
package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
)

func index(w http.ResponseWriter, r *http.Request) {
    if r.RequestURI != "/" {
        w.WriteHeader(404)
        return
    }
    fmt.Fprintf(w, "%s\n", "Hello Wrold!")
    fmt.Fprintf(w, "You are in the index\n")
}

func login(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    // 打印Content-Type为application/x-www-form-urlencoded的数据
    if len(r.Form) > 0 {
        for k, v := range r.Form {
            fmt.Printf("%s=%s\n", k, v[0])
        }
    }
    fmt.Fprintf(w, "You are in the login\n")
}

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/", index)
    mux.HandleFunc("/login", login)

    cert, err := tls.LoadX509KeyPair("./server.pem", "./server.key")
    if err != nil {
        fmt.Println(err)
        return
    }

    server := &http.Server{
        Addr:    "0.0.0.0:9090",
        Handler: mux,
        TLSConfig: &tls.Config{
            Certificates: []tls.Certificate{cert},
        },
    }

    server.ListenAndServeTLS("", "")
}

使用POST发送带参数且Content-Type为application/json的请求

// client
package main

import (
    "bytes"
    "crypto/tls"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // 结构体转json
    type Account struct {
        Email    string `json: "email"`
        Password string `json: "password"`
    }

    account := Account{
        Email:    "xx@xx.com",
        Password: "123456",
    }

    params, err := json.Marshal(account)
    //string(params): {"Email":"xx@xx.com","Password":"123456"}

    req, err := http.NewRequest("POST", "https://localhost:9090/login", bytes.NewBuffer(params))

    if err != nil {
        fmt.Println(err)
        return
    }

    req.Header.Add("Content-Type", "application/json")

    tr := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }

    client := &http.Client{
        Transport: tr,
    }

    resp, err := client.Do(req)

    if err != nil {
        fmt.Println(err)
        return
    }

    result, err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s", result)
}
// service
package main

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

func index(w http.ResponseWriter, r *http.Request) {
    if r.RequestURI != "/" {
        w.WriteHeader(404)
        return
    }
    fmt.Fprintf(w, "%s\n", "Hello Wrold!")
    fmt.Fprintf(w, "You are in the index\n")
}

func login(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    // 打印Content-Type为application/json的数据
    data, _ := ioutil.ReadAll(r.Body)
    fmt.Println(string(data))
    fmt.Fprintf(w, "You are in the login\n")
}

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/", index)
    mux.HandleFunc("/login", login)

    cert, err := tls.LoadX509KeyPair("./server.pem", "./server.key")
    if err != nil {
        fmt.Println(err)
        return
    }

    server := &http.Server{
        Addr:    "0.0.0.0:9090",
        Handler: mux,
        TLSConfig: &tls.Config{
            Certificates: []tls.Certificate{cert},
        },
    }

    server.ListenAndServeTLS("", "")
}
Last modification:October 28th, 2019 at 02:44 pm
If you think my article is useful to you, please feel free to appreciate