【GoLang】golang HTTP GET/POST JSON的服務端、客戶端示例,包含序列化、反序列化


服務端代碼示例:

package main

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

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func index(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    fmt.Println("Form: ", r.Form)
    fmt.Println("Path: ", r.URL.Path)
    fmt.Println(r.Form["a"])
    fmt.Println(r.Form["b"])
    for k, v := range r.Form {
        fmt.Println(k, "=>", v, strings.Join(v, "-"))
    }
    fmt.Fprint(w, "It works !")
}

func test(w http.ResponseWriter, r *http.Request) {
    body, _ := ioutil.ReadAll(r.Body)
    //    r.Body.Close()
    body_str := string(body)
    fmt.Println(body_str)
    //    fmt.Fprint(w, body_str)
    var user User
    //    user.Name = "aaa"
    //    user.Age = 99
    //    if bs, err := json.Marshal(user); err == nil {
    //        fmt.Println(string(bs))
    //    } else {
    //        fmt.Println(err)
    //    }

    if err := json.Unmarshal(body, &user); err == nil {
        fmt.Println(user)
        user.Age += 100
        fmt.Println(user)
        ret, _ := json.Marshal(user)
        fmt.Fprint(w, string(ret))
    } else {
        fmt.Println(err)
    }
}

func main() {
    http.HandleFunc("/", index)
    http.HandleFunc("/test/", test)

    if err := http.ListenAndServe("0.0.0.0:8080", nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

客戶端代碼示例:

package main

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

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    resp, _ := http.Get("http://10.67.2.252:8080/?a=123456&b=aaa&b=bbb")
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))

    var user User
    user.Name = "aaa"
    user.Age = 99
    if bs, err := json.Marshal(user); err == nil {
        //        fmt.Println(string(bs))
        req := bytes.NewBuffer([]byte(bs))
        tmp := `{"name":"junneyang", "age": 88}`
        req = bytes.NewBuffer([]byte(tmp))

        body_type := "application/json;charset=utf-8"
        resp, _ = http.Post("http://10.67.2.252:8080/test/", body_type, req)
        body, _ = ioutil.ReadAll(resp.Body)
        fmt.Println(string(body))
    } else {
        fmt.Println(err)
    }

    client := &http.Client{}
    request, _ := http.NewRequest("GET", "http://10.67.2.252:8080/?a=123456&b=aaa&b=bbb", nil)
    request.Header.Set("Connection", "keep-alive")
    response, _ := client.Do(request)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
    }

    req := `{"name":"junneyang", "age": 88}`
    req_new := bytes.NewBuffer([]byte(req))
    request, _ = http.NewRequest("POST", "http://10.67.2.252:8080/test/", req_new)
    request.Header.Set("Content-type", "application/json")
    response, _ = client.Do(request)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
    }
}

 

參考資料:

golang json.Marshal struct_百度搜索
golang json 成結構體 詳解 - 為程序員服務
golang的json操作 - liaojie的個人頁面 - 開源中國社區
go語言 獲取post方式json | Go語言中文網 | Golang中文社區 | Golang中國
Golang Web編程的Get和Post請求發送與解析 - 推酷
go post json 遇到的問題 | Go語言中文網 | Golang中文社區 | Golang中國
Go語言_HTTP包 - 軒脈刃 - 博客園
golang中net/http包用法 | Go語言中文網 | Golang中文社區 | Golang中國
golang使用http client發起get和post請求示例 - 快樂編程
使用Golang 搭建http web服務器 - 軒脈刃 - 博客園
Golang Http Server源碼閱讀 - 軒脈刃 - 博客園
golang中發送http請求的幾種常見情況 | Go語言中文網 | Golang中文社區 | Golang中國
golang語言中發起http請求 | Go語言中文網 | Golang中文社區 | Golang中國

golang http請求優化: https://www.douban.com/note/285372115/

goreq: 極簡單的流式golang http client:  http://www.tuicool.com/articles/FNZbYjj

golang的http client源碼簡析:  http://studygolang.com/articles/5774

http://www.oschina.net/question/593413_119339


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM