1. 程式人生 > >go http client, http server

go http client, http server

only lock nan ret str net con iou main

Go語言中的HTTP client, server非常簡單。具體如下。

HTTP Server

package  main

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

)


func main() {

        http.HandleFunc("/bar", func (w http.ResponseWriter, r *http.Request){
                fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))

                if r.Method == "POST" {
                        b, err := ioutil.ReadAll(r.Body)
                        if err != nil {
                                log.Println("Read failed:", err)
                        }
                        defer r.Body.Close()


                        log.Println("b:", string(b))
                } else {

                        log.Println("ONly support Post")
                        w.Write([]byte("Only support post"))
                }

        })

        log.Fatal(http.ListenAndServe(":8080", nil))

}

HTTP Client

  1. GET方式

    package main
    
    import (
            "io/ioutil"
            "log"
            "net/http"
    
    )
    
    
    func main() {
    
            url := "http://127.0.0.1:8080/bar"
    
            resp, err := http.Get(url)
            if err != nil {
                    log.Println("Get failed:", err)
                    return
            }
    
            defer resp.Body.Close()
    
            if resp.StatusCode != http.StatusOK {
                    log.Println("statuscode:", resp.StatusCode)
    
            }
    
            content, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                    log.Println("Read failed:", err)
            }
    
    
            log.Println("content:", string(content))
    
    }
  2. POST方式

    package main
    
    import (
            "bytes"
            "io/ioutil"
            "log"
            "net/http"
    
    )
    
    
    func main() {
    
            url := "http://127.0.0.1:8080/bar"
            contentType := "application/json;charset=utf-8"
    
            b := []byte("Hello, Server")
            body := bytes.NewBuffer(b)
    
            resp, err := http.Post(url, contentType, body)
            if err != nil {
                    log.Println("Post failed:", err)
                    return
            }
    
            defer resp.Body.Close()
    
    
            content, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                    log.Println("Read failed:", err)
                    return
            }
    
    
            log.Println("content:", string(content))
    
    }
    

註意:
response的Body使用後記得close,即:

resp.Body.Close()

關於如何傳遞json格式數據,可以參考博文go http 傳遞json數據

go http client, http server