[Code articles] Build your own golang framework step by step from scratch (6)

Basically, after getting this basic framework, you can make some changes you want to make. For example, if you want to add a queue plugin, you can modify it in the corresponding directory, but I want to make it more general. This article will start a websocket service and change the configuration file to yaml format.

Change setting

There are several reasons why you want to change the configuration from json to yaml:

  1. json is mainly used for information transmission, and yaml is more suitable for use as a configuration file format, the purpose of the two is different;
  2. The yaml format looks clearer than json;
  3. You can add comments in the yaml file to make the configuration easier to understand.

Here, the package used to parse the yaml file is "gopkg.in/yaml.v2". Examples can be found on github, and a link to this project can be found at the end of the article.

Add websocket services to the framework

I hope this project can cover some basic functions as much as possible, so I added a websocket interface to it to see how I did it.

As mentioned before, the specific processing logic of this project will be carried out under process / controller, while the interface level is distributed under the http and rpc directories. Before adding websocket into this framework, we must first know: websocket is a protocol, a protocol that upgrades on http, so it does not listen to the port directly like we opened the http service before, but on http Open an interface on the service, through the interface to achieve the connection between the server and the client, well, after clarifying this, let's take a look at how to achieve the code.

First, we add a route.

engine.GET("/ws", Ws)

Then, implement the handler–Ws that the route points to.

func Ws(ctx *gin.Context) {
	ws, err := upGrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		return
	}
	defer ws.Close()
	for {
		//读取数据
		mt, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		if string(message) == "ping" {
			message = []byte("pong")
		}
		if string(message) == "server_time" {
			resp, _, _ := controller.GetServerTime()
			serverTime := strconv.FormatInt(resp.ServerTime, 10)
			message = []byte(serverTime)
		}
		//写入数据
		err = ws.WriteMessage(mt, message)
		if err != nil {
			break
		}
	}
}

Note that this sentence code:

ws, err := upGrader.Upgrade(ctx.Writer, ctx.Request, nil)

As mentioned earlier, websocket is a protocol, a protocol on top of http, so we "upgrade" http. A for loop is also used in the code, which is very much like http monitoring. In order to unify, we call controller.GetServerTime () to get the system time, which makes the http interface and ws interface unified, and the real implementation logic is in the controller.

Next, we write a client to test:

func TestWs(t *testing.T) {
	var dialer *websocket.Dialer

	conn, _, err := dialer.Dial("ws://127.0.0.1:8080/ws", nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	go timeWriter(conn)

	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("read:", err)
			return
		}

		fmt.Printf("received: %s\n", message)
	}
}

func timeWriter(conn *websocket.Conn) {
	for {
		time.Sleep(time.Second * 2)
		conn.WriteMessage(websocket.TextMessage, []byte(time.Now().Format("2006-01-02 15:04:05")))
		conn.WriteMessage(websocket.TextMessage, []byte("ping"))
		conn.WriteMessage(websocket.TextMessage, []byte("server_time"))
	}
}

So far, we have added the websocket function to this framework, and changed the format of the configuration file from json to yaml, which looks more clear.

For the complete code, please see: https://github.com/TomatoMr/awesomeframework .


Welcome to pay attention to my public number: onepunchgo, leave me a message.

image

Published 20 original articles · Likes0 · Visits 765

Guess you like

Origin blog.csdn.net/qq_31362439/article/details/104324603