Project examples have been posted to Github welcome Star

The project address

Install the article

windows

Download address

Next all the way

Check whether the installation is successful

 go version
 
Copy the code

mac

Methods a

brew install go
Copy the code

Method two is faster

download

The installation

validation

The universal Hello Word

Create the hello.go file

package main

import "fmt"

func main() {
   fmt.Println("Hello, World!")
}
Copy the code

run

go run hello.go
Copy the code

run

go build hello.go
./hello
Copy the code

VsCode extension

Mirror proxy -Goproxy China

The environment variable

Vim ~/.zshrc or vim. Bash_profile

Export GOROOT=/usr/local/go export GOPATH=~/go export PATH=${PATH}:$GOPATH/binCopy the code

Run source ~/.zshrc or source ~/.bash_profile to take effect

Check the command

go env
Copy the code

WebSocket

The WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.

Its biggest feature is that the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, is a real two-way equal dialogue, belongs to a server push technology.

github.com/gorilla/websocket

Go websocket library

access

go get github.com/gorilla/websocket
Copy the code

Using document

Enter the theme

The project structure

  • realTimeChat
    • src
      • main.js
    • web
    • go.mod

SRC project built for the go program directory web // vue-cli go.mod is for dependency package management (recording and resolving dependencies on other modules)

Generation mode Run the following command

CD RealTimeChat go mod init SRC // init following the name of the directory where main.js residesCopy the code

Web project creation please move to

Vue – CLI setup project creation and basic configuration

The main program main. Go

Package the main import (" encoding/json "/ / json format" FMT "".net/HTTP / / HTTP service" "github.com/gorilla/websocket") / / map map, Its key corresponds to a pointer to the WebSocket, and its value is a Boolean. We don't actually need this value, but the mapping data structure we use needs to have a mapping value to make it easier to add and remove items. Var clients = make(map[* websocket.conn]bool) var broadcast = make(chan Message) // Upgrader Upgrade HTTP requests to the WebSocket var upgrader = websocket.upgrader { func(r *http.Request) bool { return true }, } // Client unique ID type userInfo struct {UserId string Code string} // User information + Message content type Message struct {Msg string Json :" MSG "' Username string 'JSON :" Username"'} // The Upgrade function upgrades HTTP to the WebSocket protocol func Handler (w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, Nil) var info userInfo info.userid = ws.remoteAddr ().string () info.code = "auth" data, Ws.writemessage (WebSocket.TextMessage, []byte(string(data))) FMT.Println(" user :", Ws.remoteaddr ().string (), "join ") if err! = nil {fmt.println (err) return} // Close the connection on exit as deferred ws.close () // Add the new client to the global "Clients" map to register clients[ws] = true // For {var MSG Message // Reads the next JSON-encoded Message from the connection and stores it in the value pointed to by MSG. err := ws.ReadJSON(&msg) if err ! = nil { fmt.Println(err) delete(clients, Ws) break} // broadcast < -msg}} // func handleMessages() {for {// read handleMessages from "broadcast" continuously MSG := For client := range clients {fmt.println ('2') // WriteJSON writes the JSON encoding of MSG as a message err := client.WriteJSON(&msg) if err ! = nil {fmt.println (err) client.close () delete(clients, client)}}}} func main() {// Print output information. fmt.Println("ListenAndServe: ListenAndServe(":8000", nil) if err! = nil { fmt.Println("ListenAndServe") fmt.Println(err) } }Copy the code

SRC directory

go run main.go
Copy the code

Web vue Main logic

. mounted() { var self = this; this.ws = new WebSocket('ws://localhost:8000/ws'); This.ws.addeventlistener ('message', function(e) {var res = json.parse (e.ata); If (res.code === 'auth'){self.form.username = res.userid.replace (RegExp('\\[::1]:', 'g'); ") self.upuser_id (self.form.username) return} var type = res.username == self.userid? 'right' : 'left' // Store the message to self.addMessage(object.assign ({type: type},res))}); }, methods:{ ... mapActions('user', ['upUSER_ID']), ... Submit () {this.ws.send(json.ify ({MSG: this.form.msg, username: this.form.username })); this.form.msg = '' }, } ...Copy the code

rendering

Go Run main.go ListenAndServe: 8000 User: [::1]:55023 Join user: [::1]:55055 Join webSocket: close 1001 (going Away) User: [: : 1) : 55062Copy the code


To be continued, the function is relatively simple, the registration and login, friend list, chat record, send private message, as envisaged before, due to the limited time has not been able to achieve, continue to improve later

Leave a comment in the comments section if you can

🏆 technology project phase ii | and I Go those things…