【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

posted @ 2016-12-22 14:41 junneyang 阅读(...) 评论(...) 编辑 收藏