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))
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章