golang简单的http server与client

http server

package main

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

type HttpData struct {
	Flag int    `json:"flag"`
	Msg  string `json:"msg"`
}

func HelloWorld(w http.ResponseWriter,r *http.Request){
	req,err:= ioutil.ReadAll(r.Body)
	if err!=nil{
		fmt.Println("fail",err)
		return
	}
	fmt.Printf("%s",req)
	var requestBody HttpData
	err=json.Unmarshal(req,&requestBody)
	if err!=nil{
		fmt.Println("数据err:",err)
	}

	respBody:= struct {
		Code int
		HttpData
	}{
		Code:200,
		HttpData:requestBody,
	}
	resp,err:= json.Marshal(respBody)
	if err!=nil{
		fmt.Fprintf(w,"失败")
	}
	fmt.Fprintf(w,string(resp))

}
func main(){
	http.HandleFunc("/hello",HelloWorld)
	fmt.Println("listen on 8080")
	http.ListenAndServe(":8080",nil)

}

client

package main

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

type HttpData struct {
	Flag int    `json:"flag"`
	Msg  string `json:"msg"`
}

func main() {

	url := "http://127.0.0.1:8080/hello"
	contentType := "application/json;charset=utf-8"

	httpdata:=HttpData{
		1,
		"hello",
	}

	b, err := json.Marshal(httpdata)
	if err != nil {
		fmt.Println("json format error:", err)
		return
	}

	body := bytes.NewBuffer(b)

	resp, err := http.Post(url, contentType, body)
	if err != nil {
		fmt.Println("Post failed:", err)
		return
	}

	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Read failed:", err)
		return
	}

	fmt.Println("header:", resp.Header)
	fmt.Println("content:", string(content))
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值