#1 Simple GET request

package main

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

func main(a) {

    resp, err := http.Get("https://juejin.cn/")

    iferr ! =nil {
        log.Fatal(err)
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    iferr ! =nil {

        log.Fatal(err)
    }

    fmt.Println(string(body))
}
Copy the code

#2 Get requests take parameters

package main

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

func main(a) {

    query := "golang gin"
    type: =0

    params := "query=" + url.QueryEscape(query) + "&" +
        "type=" + url.QueryEscape(type)
    path := fmt.Sprintf("https://juejin.cn/search?%s", params)

    resp, err := http.Get(path)

    iferr ! =nil {
        log.Fatal(err)
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    iferr ! =nil {

        log.Fatal(err)
    }

    fmt.Println(string(body))
}
Copy the code

#3 Form parameter POST request

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
)

func main(a) {

    data := url.Values{
        "name":       {"John Doe"},
        "occupation": {"gardener"},
    }

    resp, err := http.PostForm("https://httpbin.org/post", data)

    iferr ! =nil {
        log.Fatal(err)
    }

    var res map[string]interface{}

    json.NewDecoder(resp.Body).Decode(&res)

    fmt.Println(res["form"])}Copy the code

#4 JSON parameter POST request

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

func main(a) {

    values := map[string]string{"name": "John Doe"."occupation": "gardener"}
    json_data, err := json.Marshal(values)

    iferr ! =nil {
        log.Fatal(err)
    }

    resp, err := http.Post("https://httpbin.org/post"."application/json",
        bytes.NewBuffer(json_data))

    iferr ! =nil {
        log.Fatal(err)
    }

    var res map[string]interface{}

    json.NewDecoder(resp.Body).Decode(&res)

    fmt.Println(res["json"])}Copy the code