What does Go do
Hello, I am the good guy, the author of comic Book Go language. This time I’m going to share with you some information about Go. As a programmer, in this era, master a technology, just like a good martial arts, not only through continuous combat experience, but also have enough enthusiasm, step by step to reach the realm of the master. In many development languages, how to find a suitable for their practice of martial arts secrets. You have to know something about the language. Know its power, to better grasp, become a master is just around the corner.
How powerful can Go be as a back-end language, what can it do, and what moves can it make you want to learn it? So the next simple show a few moves, but also hope you big guys advice!
Gocv computer vision
OpenCV is a cross-platform computer vision and machine learning software library distributed under the BSD license (open source) that runs on Linux, Windows, Android, and Mac OS operating systems. Many general algorithms in image processing and computer vision are implemented. OpenCV is written in C++, it has C++, Python, Java and MATLAB interfaces, and supports Windows, Linux, Android and Mac OS, OpenCV mainly tends to real-time visual applications, now also provides for C#, Ch, Ruby, GO support is also known as GOCV.https://gocv.io/
- Install gocv
go get -u -d gocv.io/x/gocv
- Install MinGW – W64
https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/7.3.0/
- Install CMake
https://cmake.org/download/
- Install and compile GoCV
chdir %GOPATH%\src\gocv.io\x\gocv win_build_opencv.cmd Copy the code
Gocv binaries the image
package main
import (
"gocv.io/x/gocv"
)
// Test examples
func main(a) {
filename := "test.png"
window := gocv.NewWindow("Hello")
img := gocv.IMRead(filename, gocv.IMReadColor)
destImage := gocv.NewMat()
// Convert to grayscale
gocv.CvtColor(img, &destImage, gocv.ColorBGRToGray)
for {
window.IMShow(destImage)
if window.WaitKey(1) > =0 {
break}}}Copy the code
Gocv face detection
package main
import (
"fmt"
"image"
"image/color"
"os"
"gocv.io/x/gocv"
)
func main(a) {
if len(os.Args) < 3 {
fmt.Println("How to run:\n\tfacedetect [camera ID] [classifier XML file]")
return
}
// parse args
deviceID := os.Args[1]
xmlFile := os.Args[2]
// open webcam
webcam, err := gocv.OpenVideoCapture(deviceID)
iferr ! =nil {
fmt.Printf("error opening video capture device: %v\n", deviceID)
return
}
defer webcam.Close()
// open display window
window := gocv.NewWindow("Face Detect")
defer window.Close()
// prepare image matrix
img := gocv.NewMat()
defer img.Close()
// color for the rect when faces detected
blue := color.RGBA{0.0.255.0}
// load classifier to recognize faces
classifier := gocv.NewCascadeClassifier()
defer classifier.Close()
if! classifier.Load(xmlFile) { fmt.Printf("Error reading cascade file: %v\n", xmlFile)
return
}
fmt.Printf("Start reading device: %v\n", deviceID)
for {
ifok := webcam.Read(&img); ! ok { fmt.Printf("Device closed: %v\n", deviceID)
return
}
if img.Empty() {
continue
}
// detect faces
rects := classifier.DetectMultiScale(img)
fmt.Printf("found %d faces\n".len(rects))
// draw a rectangle around each face on the original image,
// along with text identifing as "Human"
for _, r := range rects {
gocv.Rectangle(&img, r, blue, 3)
size := gocv.GetTextSize("Human", gocv.FontHersheyPlain, 1.2.2)
pt := image.Pt(r.Min.X+(r.Min.X/2)-(size.X/2), r.Min.Y2 -)
gocv.PutText(&img, "Human", pt, gocv.FontHersheyPlain, 1.2, blue, 2)}// show the image in the window, and wait 1 millisecond
window.IMShow(img)
if window.WaitKey(1) > =0 {
break}}}Copy the code
Gobot robot
Gobot is an IoT framework written in Go for robots, drones and the Internet of Things.https://gobot.io/
- Support for 35 different platforms.
- A device that supports input/output (GPIO) communication.
- Simulate I/O (AIO) drivers.
- I2C driver.
- SPI drive.
Raspberry pie
Raspberry Pi is ChineseRaspberry pie
For short,RPi
A microcomputer the size of a credit card and based on Linux, it is an ARM-based microcomputer motherboard. Connects to a keyboard, mouse, and network cable, providing the basic functions of a PC. The latest version of the Raspberry PI 4B has 4 gigabytes of memory, introduces USB 3.0, supports dual-screen 4K output, and has faster CPU and GPU speeds.
The Go program runs on raspberry PI to implement the tank robot.
package drivers
// import "fmt"
type Motor struct {
PWMA int
AIN1 int
AIN2 int
BIN1 int
BIN2 int
PWMB int
Driver *PCA9685Driver
Debug bool
}
type MotorPosition int
const (
MotorPosition_Left MotorPosition = 0
MotorPosition_Right MotorPosition = 1
MotorPosition_All MotorPosition = - 1
)
type MotorDirection int
const (
MotorDirection_Forward MotorDirection = 1
MotorDirection_Backward MotorDirection = - 1
)
func NewMotor(driver *PCA9685Driver) *Motor {
motor := &Motor{
PWMA: 0,
AIN1: 1,
AIN2: 2,
BIN1: 3,
BIN2: 4,
PWMB: 5,
Driver: driver,
Debug: false,}var PWM float32 = 125
// fmt.Println(" Set PWM speed :", PWM)
driver.SetPWMFreq(PWM)
return motor
}
/ / to go forward
func (this *Motor) Forward(speed int) {
this.Run(MotorPosition_All, MotorDirection_Forward, speed)
}
/ / back
func (this *Motor) Backward(speed int) {
this.Run(MotorPosition_All, MotorDirection_Backward, speed)
}
// Turn left, turn on the same spot
func (this *Motor) Left(speed int) {
this.Run(MotorPosition_Left, MotorDirection_Backward, speed)
this.Run(MotorPosition_Right, MotorDirection_Forward, speed)
}
// Turn right, turn in place
func (this *Motor) Right(speed int) {
this.Run(MotorPosition_Right, MotorDirection_Backward, speed)
this.Run(MotorPosition_Left, MotorDirection_Forward, speed)
}
// Direct operation of the motor
func (this *Motor) Run(motor MotorPosition, direction MotorDirection, speed int) {
if speed > 100 {
speed = 100
}
// Operate all motors simultaneously
if motor == MotorPosition_All {
this.Run(MotorPosition_Left, direction, speed)
this.Run(MotorPosition_Right, direction, speed)
return
}
// Set the default PWM speed control channel to motor A speed control channel
pwmChannel := this.PWMA
// Set the default operating motor to A
PIN1 := this.AIN1
PIN2 := this.AIN2
// Operate motor and speed control channel as motor B according to parameter Settings
if motor == MotorPosition_Right {
pwmChannel = this.PWMB
PIN1 = this.BIN1
PIN2 = this.BIN2
}
// If the argument is back, reverse the positions of PIN1 and PIN2
if direction == MotorDirection_Backward {
PIN1, PIN2 = PIN2, PIN1
}
// fmt.Println("pwmChannel:", pwmChannel, ",speed:", speed, ",PIN1:", PIN1, ",PIN2:", PIN2)
// Set the speed
this.Driver.SetPWM(pwmChannel, 0.uint16(speed*(4096/100)))
// Set the positive electrode
this.Driver.SetPWM(PIN1, 0.4095)
// Set the negative electrode
this.Driver.SetPWM(PIN2, 0.0)}// func (this *Motor) SetPWM(channel int, on uint16, off uint16) (err error) {
// this.Driver
// if _, err := p.connection.Write([]byte{byte(PCA9685_LED0_ON_L + 4*channel), byte(on), byte(on >> 8), byte(off), byte(off >> 8)}); err != nil {
// return err
/ /}
// return
// }
func (this *Motor) MotorStop(motor MotorPosition) {
if motor == MotorPosition_All {
this.MotorStop(MotorPosition_Left)
this.MotorStop(MotorPosition_Right)
return
}
// Set the default PWM speed control channel to motor A speed control channel
pwmChannel := this.PWMA
if motor == MotorPosition_Right {
pwmChannel = this.PWMB
}
// Set the speed
this.Driver.SetPWM(pwmChannel, 0.0)}Copy the code
package core
import (
"fmt"
"gobot.io/x/gobot"
"airobot/robot/drivers"
"gobot.io/x/gobot/platforms/raspi"
)
// The main robot structure stores gobot instances and initialized drivers and operators
type Robot struct {
/ / gobot instance
gobot *gobot.Robot
// Motherboard adapter
adaptor *raspi.Adaptor
// Motor operation board drive
motorDriver *drivers.PCA9685Driver
// Motor operator
motor *drivers.Motor
// Motor operation command line up
motorCmds chan (*CMDData)
}
// Initialize the robot listener
func (this *Robot) Start(a) {
this.motorCmds = make(chan (*CMDData), 100)
go this.listenMotorCmds()
}
func (this *Robot) listenMotorCmds(a) {
m := NewMotor(this)
wait:
cmd := <-this.motorCmds
m.execute(cmd)
goto wait
}
// The robot status channel is used to inform webAPI to start. During the startup process, the channel will be pressed 0, and after the startup is complete, the channel will be pressed 1.
var RobotState = make(chan int.1)
// The robot operates the command main channel, receives the command through websocket and presses into the channel
var RobotCMD = make(chan *CMD, 100)
// Global robot instance
var bot *Robot
// Start the robot
func StartRobot(a) {
bot = &Robot{}
fmt.Println("The robot started.")
RobotState <- 0
fmt.Println("Initialize the motherboard adapter.")
bot.adaptor = raspi.NewAdaptor()
fmt.Println("Initialize the motor drive.")
bot.motorDriver = drivers.NewPCA9685Driver(bot.adaptor)
bot.Start()
work := func(a) {
fmt.Println("Initialize the motor operator.")
bot.motor = drivers.NewMotor(bot.motorDriver)
// var PWM float32 = 125
// fmt.Println(" Set PWM speed :", PWM)
// bot.motorDriver.SetPWMFreq(PWM)
fmt.Println("Robot startup complete.")
fmt.Println("The robot began to wait for instructions.")
RobotState <- 1
begin:
cmd := <-RobotCMD
// fmt.Println(" received command :", CMD)
switch cmd.Channel {
case "motor":
bot.motorCmds <- &cmd.Data
break
}
goto begin
}
robot := gobot.NewRobot("tankBot",
[]gobot.Connection{bot.adaptor},
[]gobot.Device{bot.motorDriver},
work,
)
robot.Start()
}
Copy the code
Live video service
Livego is a simple and efficient live broadcast server written in pure GO language. https://github.com/gwuhaolin/livego
- Supported transport protocols
RTMP
.AMF
.HLS
.HTTP-FLV
- Supported container formats
FLV
.TS
- Supported encoding format
H264
.AAC
.MP3
use
- 1 Start the LiveGo service: Run the LiveGo binary file to start the LiveGo service.
- 2 go to http://localhost:8090/control/get? Room =movie Gets a room’s Channelkey (channelkey is used to push streams, movie is used to play).
- 3 Push stream: Push video stream to address RTMP ://localhost:1935/{appName}/{channelKey} (appName default is live)
For example, run ffmpeg-re -i demo. FLV -c copy -f FLV
rtmp://localhost:1935/{appName}/{channelkey}
Copy the code
Playback: Supports multiple playback protocols and addresses as follows: RTMP: RTMP: / / localhost: 1935 / {appname} / movie FLV: http://127.0.0.1:7001/ {appname} / movie. FLV HLS: http://127.0.0.1:7002/ {appname} / movie. M3u8
//ffmpeg command push stream
ffmpeg -re -i demo.flv -c copy -f flv rtmp://localhost:1935/{appname}/{channelkey}
Copy the code
The document address: https://github.com/gwuhaolin/livego/blob/master/README_cn.md
CRON Indicates a scheduled task
The GO language supports cron scheduled taskshttps://github.com/jakecoffman/cron
package main
import (
"fmt"
"github.com/jakecoffman/cron"
)
func main(a) {
c := cron.New()
Testfun is executed every day at 6 am
c.AddFunc("0, 0, 6 * *? ", Testfunc, "Scheduled task")
c.Start()
}
func Testfunc(a) {
fmt.Println("Scheduled task")
//TODO processing logic....
}
Copy the code
Excelize a Go version of the Excel documentation API
Go language for operating Office Excel document base library, based on ECMA-376, ISO/IEC 29500 international standard. You can use it to read and write spreadsheet documents created with Microsoft Excelβ’ 2007 and above. Support XLSX/XLSM/XLTM and other document formats, highly compatible with style, image (table), PivotTable, slicer and other complex components of the document, and provide streaming read and write API
- Document Address:
https://xuri.me/excelize/zh-hans/
- Project Address:
https://github.com/360EntSecGroup-Skylar/excelize
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main(a) {
f := excelize.NewFile()
// Create a sheet
index := f.NewSheet("Sheet1")
/ / set the value
f.SetCellValue("Sheet2"."A2"."Hello world.")
f.SetCellValue("Sheet1"."B2".100)
// Sets the active worksheet for the workbook.
f.SetActiveSheet(index)
/ / save the excel
if err := f.SaveAs("Book1.xlsx"); err ! =nil {
fmt.Println(err)
}
}
Copy the code
π technology project phase ii | and I Go those things…