AdSense

網頁

2022/4/29

Golang 發送請求 send http request

Go發送HTTP Request的方式如下。


範例環境:

  • Go 1.18


事前要求

參考「Golang http handle POST JSON to struct」建立接收請求的API http://localhost:8080/employee


發送請求

下面以http.Post()發送POST請求及JSON資料到http://localhost:8080/employee。然後從http.Response取得body寫出回應。

main.go

package main

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

type Employee struct {
    Id   int
    Name string
    Age  int
}

func main() {
    ... // GET|/employee handler, 參考:https://matthung0807.blogspot.com/2021/12/go-http-handle-post-json-to-struct.html

    http.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodGet:
            resp := Post("http://localhost:8080/employee")
            fmt.Fprint(w, resp)
        default:
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }
    })
    http.ListenAndServe(":8080", nil)
}

func Post(url string) string {
    resp, err := http.Post(
        url,                 // target url
        "application/json",  // content-type
        createRequestBody()) // request body
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close() // 記得關閉resp.Body

    if resp.StatusCode == http.StatusOK {
        b, err := io.ReadAll(resp.Body)
        if err != nil {
            panic(err)
        }
        body := string(b)
        return body
    }
    return ""
}

func createRequestBody() *bytes.Buffer {
    emp := Employee{
        Id:   1,
        Name: "john",
        Age:  33,
    }

    data, err := json.Marshal(&emp)
    if err != nil {
        panic(err)
    }

    return bytes.NewBuffer(data)
}

github


測試

啟動專案在以curl執行curl -X GET "http://localhost:8080/send"呼叫GET|/send結果如下。

$ curl -X GET "http://localhost:8080/send"
{"Id":1,"Name":"john","Age":33}

循序圖。


                  http://localhost:8080   http://localhost:8080
┌────────┐             ┌────────┐              ┌────────┐
│ client │             │ Server │              │ Server │
└────┬───┘             └────┬───┘              └────┬───┘
     │                      │                       │
     │                      │                       │
     │     GET|/send        │                       │
curl┌┼────────────────────►┌┤                       │
    ││                     ││                       │
    ││                     ││     POST/empoyee      │
    ││            http.Post│┼─────────────────────►┌┤
    ││                     ││                      ││
    ││                     ││                      ││
    ││                     ││                      ││
    ││                     │┤◄─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┴┤
    ││                     ││                       │
    ││                     │┼─print resp.Body       │
    │┤◄─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴┤                       │
    ││                      │                       │
    └┤                      │                       │
     │                      │                       │
     │                      │                       │
     ▼                      ▼                       ▼


沒有留言:

AdSense