go 语言------web通信

第一种直接用http包来编写,我觉得这种方式给转语言的人来说会比较好理解

服务器端(server):

package main

import (
	"encoding/json"
	"net/http"
	"fmt"
	"io/ioutil"
	"log"
)
type Cmd struct {
	Req int
	Name string
}

func main() {
    //设置路由,例如:当url为127.0.0.1:9090/test时会调用deal函数
	http.HandleFunc("/test",deal)

    //监听ip地址和端口,建立连接,接受客户端的请求。第二个参数是服务器处理程序,一般为空,
	err:=http.ListenAndServe(":9090", nil)

	log.Fatal(err)
}
//请求通过参数传递过来,具体处理请求
func deal(w http.ResponseWriter, r *http.Request){
	t:= &Cmd{}
	if r.Method == "POST" {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Println("Read failed:", err)
		}
		defer r.Body.Close()

        //将json消息转成结构体
		err = json.Unmarshal(b, t)
		if err != nil {
			log.Println("json format error:", err)
		}
		log.Println("tasklog:", t)

	} 
}

客户端(client):

package main

import (
	"encoding/json"
	"bytes"
	"net/http"
	"io/ioutil"
	"log"
	"fmt"
)
type Cmd struct {
	Req int
	Name string
}

func main() {

	url := "http://127.0.0.1:9090/test"
	contentType := "application/json;charset=utf-8"

	cmd := Cmd{Req: 12, Name: "plugin"}
    
    //将结构体转为json格式
	b ,err := json.Marshal(cmd)
	body := bytes.NewBuffer(b)
 
    //发送post请求
	resp, err := http.Post(url, contentType, body)
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println("Read failed:", err)
		return
	}
	log.Println("content:", string(content))

}

第二种使用gin包来编写。

服务器端:

package main

import (
	"encoding/json"
	"net/http"
	"github.com/gin-gonic/gin"
	"fmt"
)


type Cmd struct {
	Req int
	Name string
}
func main(){
	router := gin.New()
	router.Use(gin.Logger(), gin.Recovery())

	//:name  支持可变,自己决定填什么
	router.POST("/test/:name",dealpost)

	router.GET("/test/:name",dealget)

	//建立连接,接听端口
	router.Run("0.0.0.0:9090")
}

var cmd_arr []*Cmd

func dealpost(c *gin.Context){
	cmd:=Cmd{}

	//可以获得url上的可变参
	name := c.Param("name")

	// urlencoded form or multipart form 从中根据key找value
	res:=c.PostForm("context")

	json.Unmarshal([]byte(res), &cmd)
	add(&cmd)
	fmt.Println(cmd)
	//JSON将给定结构序列化为JSON到响应主体中,还将Content-Type设置为“application / json”
	c.JSON(http.StatusOK,name)
}
func add(c *Cmd){
	cmd_arr=append(cmd_arr,c)
}
func dealget(c *gin.Context){
	for _,v:=range cmd_arr{
		c.JSON(http.StatusOK,v)
	}
}

客户端:

package main

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

type Cmd struct {

	Req int
	Name string

}
func main(){
    cmd:=Cmd{12,"hello"}

    b,_:=json.Marshal(cmd)
	reader := bytes.NewReader(b)

	if req, err:= http.NewRequest("POST", "127.0.0.1:9090", reader); err == nil {
		client := &http.Client{}
		var resp *http.Response
		resp, err = client.Do(req)
		fmt.Println(resp)
	}
}

 

你可能感兴趣的:(go 语言------web通信)