当前位置:网站首页>Great golang Road
Great golang Road
2022-07-29 10:58:00 【wangwei830】
Golang The way
download
https://golang.google.cn/
https://golang.google.cn/dl/
edition : go.1.18
install
- GOROOT=D:\go1.18
- GOPATH=D:\gopath1.18
- GO111MODULE=on
- GOPROXY=https://goproxy.cn,direct
go mod Create project
- new directory : D:\gopath1.18\cdr
- Go to this directory : …
- Initialize project : go mod init cdr
- Download package : go get github.com/gin-gonic/gin ( Now finish here :D:\gopath1.18\pkg\mod)
- Refresh package : go mod tidy
- Goland Open the project ,import Then catalogue according to the red line index, Start silky again
gin
Online document : https://www.itying.com/gin
My column : https://www.itying.com/category-79-b0.html
Official website : https://gin-gonic.com/zh-cn
gin The basic structure
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.GET("/",funcName)
1.GET check
2.POST increase
3.PUT Change
4.DELETE Delete
funcName(c *gin.Context){
c.string(200,"aaaaaaaaaaa")
}
1. c.string Return string
2. c.json return json
3. c.jsonp return jsonp
4. c.xml return xml
5. c.html Back to the web , You need to load the template first :r.LoadHTMLGlob("templates/*") {
{
. Variable name }}
r.Run(":8080")
gin How to configure templates in different directories
// engine
r.LoadHTMLGlob("templates/**/*")
// Name the template
{
{
define "aaa/a111.html" }}
{
{
end }}
// The routing method uses templates
c.html(200,"aaa/a111.html",map[string]{
})
gin Template nesting
{
{
template "aaa/a111.html" . }}
gin Front end variables
{
{
$a := .name }}
gin Remove spaces from the front
{
{
- .name -}}
gin Front end comparison function
eq lt gt le ge ne
gin Front end condition judgment
{
{
if gt .score 80 }}
good
{
{
else if gt $score 60 }}
pass
{
{
else }}
fail,
{
{
end }}
gin front end range loop
<dl>
{
{
range $i,$v := .obj }}
<li> {
{
key by $i, The value is $v }} </li>
{
{
else }}
a Array is empty
{
{
end }}
</dl>
gin front end with deconstruction
{
{
with .atype }}
// then a The structure is assigned to . 了
gin Front end predefined functions
and , or , not , len , index
gin Custom function
r.SetFuncMap(template.FuncMap{
"formatDate":formatAsDate,
})
gin Static file service
func main(){
r := gin.Default()
r.Static("/static","./static")
}
// Put the program in the directory s The catalogue is mapped to s route
get The value to go
r.GET("/getValue",func(c *gin.Context){
username := c.Query("username")
age := c.Query("age")
page := c.DefaultQuery("page","2")
c.JSON(200,gin.H{
"username" : username,
"age" : age,
"page" : page,
})
})
// test : http://1.1.1.1:8080/getValue?username=%E6%B1%AA%E4%BC%9F&age=99
post The value to go
// Go to the form page
r.GET("/addUser",func(c *gin.Context){
c.HTML(200,"default/addUser.html",map[string]interface{
}{
})
})
<!-- Submit the form to the route -->
<form action="/doAddUser" method="post">
user name :<input type="text" name="username" /> <br><br>
The secret code :<input type="password" name="password" /> <br><br>
<input type="submit" value=" Submit ">
</form>
// Execute route post Method ,golang Get form values
r.POST("/doAddUser", func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
age := c.DefaultPostForm("age", "26")
c.JSON(200, gin.H{
"username": username,
"password": password,
"age": age,
})
})
get Pass value binding to structure
type UserInfo struct{
Username string `json:"username" form:"username"`
Password string `json:"password" form:"password"`
}
r.GET("/getUser",func(c *gin.Context){
user := &UserInfo{
}
if err := c.ShouldBind(&user); err == nil {
c.JSON(200,user)
} else {
c.JSON(200,gin.H{
"ERR" : err.Error(),
})
}
})
// test : http://1.1.1.1:8080/getUser?username=%E6%B1%AA%E4%BC%9F&password=0998*aa
post Pass value binding to structure
// Go to the form page
r.GET("/addUser",func(c *gin.Context){
c.HTML(200,"default/addUser.html",map[string]interface{
}{
})
})
<!-- Submit the form to the route -->
<form action="/doAddUser2" method="post">
user name :<input type="text" name="username" /> <br><br>
The secret code :<input type="password" name="password" /> <br><br>
<input type="submit" value=" Submit ">
</form>
r.POST("/doAddUser2",func(c *gin.Context){
user := &UserInfo{
}
if err := c.ShouldBind(&user); err == nil {
c.JSON(200,user)
} else {
c.JSON(400,gin.H{
"ERR" : err.Error(),
})
}
})
xml Data binding to structure
<?xml version="1.0" encoding="UTF-8"?>
<article>
<content type="string"> I am Zhang San. </content>
<title type="string"> Zhang San </title>
</article>
type Article struct{
Title string `json:"title" xml:"title"`
Content string `json:"content" xml:"content"`
}
r.POST("/xml",func(c *gin.Context){
article := &Article{
}
xmlSliceDate,_ = c.GetRawDate() // obtain c.Request.Body Byte stream
if err := xml.Unmarshal(xmlSliceDate,&article); err == nil {
c.JSON(200,article)
} else {
c.JSON(400,gin.H{
"ERR" : err.Error(),
})
}
})
gin Dynamic routing
r.GET("/list/:cid", func(c *gin.Context){
cid := c.Param("cid")
c.String(200,"%v",cid)
})
gin load css Document and jsp file
Reference website : https://blog.51cto.com/dongweizhen/3606790
New directory structure :
templates/statics/index.css
templates/statics/index.js
main.go Content
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"net/http"
)
func main() {
// Define a route
r := gin.Default()
// Load static file
r.Static("/dwz","templates/statics")
// Add custom functions , Parse the following “ use Baidu Search ”html Code
r.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML{
return template.HTML(str)
},
})
// Template parsing
r.LoadHTMLGlob("templates/**/*")
// Template rendering
r.GET("/posts", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts index",
})
})
r.GET("/users", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "<a href='https://www.baidu.com'> use Baidu Search </a>",
})
})
r.Run(":9090")
}
templates/statics/index.css Content
body {
background-color: cadetblue;
}
templates/statics/index.js Content
alert(123);
templates/users/index.tmpl Content
{
{
define "users/index.tmpl"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/dwz/index.css">
<title>Title</title>
</head>
<body>
{
{
.title | safe}}
<script src="/dwz/index.js"></script>
</body>
</html>
{
{
end}}
Run the program :
go run main.go
Browser access :
Log in and copy
http://ip:9090/users
Self recovery cluster start command oninitdb Design and implementation And golang Knowledge point
go perform os System commands
Reference website : https://zhuanlan.zhihu.com/p/296409942
package main
import (
"bytes"
"fmt"
"log"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l", "/var/log/*.log")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout // standard output
cmd.Stderr = &stderr // The standard error
err := cmd.Run()
outStr, errStr := stdout.String(), stderr.String()
fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)
if err != nil {
log.Fatalf("cmd.Run() failed with %s\n", err)
}
}
go send out get Request and parse the page BodyString data
Reference website :https://cloud.tencent.com/developer/article/1849807
func main(){
// Lord addrss
fmt.Println(" Remote add ")
u := "http://" + zhuip + ":" + zhuport + "/addrss?my=" + my
fmt.Println(u)
response, err := http.Get(u)
if err != nil {
fmt.Println("http.Get addrss We have an exception ")
}
buf, _ := ioutil.ReadAll(response.Body)
s := string(buf)
if s == "run addrss ok" {
fmt.Println("run addrss ok")
} else {
fmt.Println("run addrss err")
}
}
go foldback get Request and parse web page BodyJSON Data to structure
Knowledge point :
- ioutil.ReadAll(response.Body) Read all Body data
- json.Unmarshal(buf, &infoList[i]) Use a structure address resolution json character string
type Info struct {
Servername string `JSON:"servername"`
Mode string `JSON:"mode"`
Running string `JSON:"running"`
}
var infoList [3]Info
func info() {
// see db node infof
fmt.Println(" View cluster ")
for i, n := range webList {
response, err := http.Get("http://" + n.ip + ":" + n.port + "/info")
if err != nil {
fmt.Println("info API The service is not provided normally ,Docker It may have been abnormal .")
continue
}
buf, _ := ioutil.ReadAll(response.Body)
json.Unmarshal(buf, &infoList[i])
fmt.Println(infoList[i])
}
}
golang Use sftp and ssh
Reference website : https://www.programminghunter.com/article/35971402517/
sftp.go
package sshclient
import (
"fmt"
"log"
"net"
"os"
"path"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func connect(user, password, host string, port int) (*sftp.Client, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
sshClient *ssh.Client
sftpClient *sftp.Client
err error
)
// get auth method
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
hostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
}
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 1 * time.Second,
HostKeyCallback: hostKeyCallbk,
}
// connet to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
// create sftp client
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
return nil, err
}
return sftpClient, nil
}
// Send a file
func SftpPut(user, password, host, fileName string) {
var (
err error
sftpClient *sftp.Client
)
// Change here to the actual SSH Connected user name , password , Host name or IP,SSH port
sftpClient, err = connect(user, password, host, 22)
if err != nil {
log.Fatal(err)
}
defer sftpClient.Close()
// Local file path for testing and Folders on remote machines
var localFilePath = fileName
var remoteDir = "/tmp/"
srcFile, err := os.Open(localFilePath)
if err != nil {
log.Fatal(err)
}
defer srcFile.Close()
var remoteFileName = path.Base(localFilePath)
dstFile, err := sftpClient.Create(path.Join(remoteDir, remoteFileName))
if err != nil {
log.Fatal(err)
}
defer dstFile.Close()
buf := make([]byte, 1024)
for {
n, _ := srcFile.Read(buf)
if n == 0 {
break
}
dstFile.Write(buf[:n])
}
fmt.Println("copy file to remote server finished!")
}
// Download the file
func SftpGet(user, password, host, fileName string) {
var (
err error
sftpClient *sftp.Client
)
// Change here to the actual SSH Connected user name , password , Host name or IP,SSH port
sftpClient, err = connect(user, password, host, 22)
if err != nil {
log.Fatal(err)
}
defer sftpClient.Close()
// The remote file path used for testing and Local folder
var remoteFilePath = "/tmp/" + fileName
var localDir = "lib/sshclient/sftpput/"
srcFile, err := sftpClient.Open(remoteFilePath)
if err != nil {
log.Fatal(err)
}
defer srcFile.Close()
var localFileName = path.Base(remoteFilePath)
dstFile, err := os.Create(path.Join(localDir, localFileName))
if err != nil {
log.Fatal(err)
}
defer dstFile.Close()
if _, err = srcFile.WriteTo(dstFile); err != nil {
log.Fatal(err)
}
fmt.Println("copy file from remote server finished!")
}
sshclient.go
package sshclient
/* go 1.14: mkdir -p $GOPATH/src/golang.org/x/ cd $GOPATH/src/golang.org/x/ git clone https://github.com/golang/crypto.git go 1.18 go get golang.org/x/crypto/ssh */
import (
"bytes"
"fmt"
"net"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
// SSHConnect ssh Connect
func SSHConnect(user, password, host string, port int) (*ssh.Client, *ssh.Session, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
client *ssh.Client
session *ssh.Session
err error
)
// get auth method
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
hostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
}
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 1 * time.Second,
HostKeyCallback: hostKeyCallbk,
}
// connet to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, nil, err
}
// create session
if session, err = client.NewSession(); err != nil {
return client, nil, err
}
return client, session, nil
}
// RunSSHpiliang perform ssh Batch login execution
func RunSSHpiliang(user, password, host, cmdshell string) string {
var stdOut, stdErr bytes.Buffer
client, session, err := SSHConnect(user, password, host, 22)
if client != nil {
defer client.Close()
}
if session != nil {
defer session.Close()
}
if err != nil {
//fmt.Println(err," wei----------------------------------------")
if strings.Contains(err.Error(), "i/o timeout") {
return " Connect to the host 22 Error in port "
}
if strings.Contains(err.Error(), "unable to authenticate") {
return " Code or SSHKEY Error validating "
}
return " Error logging in to the host "
}
session.Stdout = &stdOut
session.Stderr = &stdErr
if err := session.Run(cmdshell); err != nil {
// fmt.Println(err.Error())
// fmt.Println(stdOut.String())
return " Error executing command !"
}
return stdOut.String()
}
golang file IO/ Catalog IO/ That's ok IO/ byte BUFIO
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func weiShuoMing() {
// Delete overwrite os.OpenFile("aaa", os.O_CREATE|os.O_RDWR, 6)
// Line write file os.Openfile("aaa", os.O_CREATE|os.O_RDWD|os.O_APPEND,6) f.WriteString("")
// reader Definition reader,err := bufio.Reader(f)
// Line read file os.Openfile("aaa",io.O_RDONLY,6) Or use os.Open("aaa") f.ReadBytes('\n')
// Offset io.Seek(-12,io.SeekBeging) also Current and End
// buf size buf := make([]byte,4096)
// Byte write file n,err:=reader.write(buf)
// Byte read file n,err:=reader.read(buf)
// Open Directory os.Openfile("aaa",io.O_RDONLY,os.ModeDir)
// Read directory entry f.Readdir(-1) return [{Size() Name() IsDir() Modetime()}...]
// https://studygolang.com/pkgdoc
// https://www.bilibili.com/video/BV1TK4y1a7ex?from=search&seid=18159148304738299137
}
func main() {
// Create overlay file
os.Create("aaa")
// Open file aaa
f, err := os.OpenFile("aaa", os.O_RDWR|os.O_APPEND, 6)
if err != nil && err != io.EOF {
fmt.Println("OpenFile Open file aaa error ")
}
defer f.Close()
// write in 5 Row data
f.WriteString(" Write data 0001\n")
f.WriteString(" Write data 0002\n Write data 0003\n")
f.WriteString(" Write data 0004\n Write data 0005\n")
// Move to the beginning of the file
f.Seek(0, io.SeekStart)
// Read the first 2,3 Row data
reader := bufio.NewReader(f)
i := 0
for {
hang, err := reader.ReadBytes('\n')
if err == io.EOF {
break
} else {
i++
}
if i == 2 || i == 3 {
fmt.Print(string(hang))
}
}
// buf read
// The offset 15 Read bytes again 12,13,14,15,16,17,18,19 Bytes (utf8 A Chinese character 3 Bytes , Line break \n For a byte )
f.Seek(15, io.SeekStart)
buf := make([]byte, 8)
f.Read(buf) // from f Read a buf The content of space , to buf assignment . This function also returns n,err among n Is the actual read slice length .
fmt.Printf("%q\n", buf)
// buf Write
f.Seek(0, io.SeekEnd)
f.Write(buf)
f.Close()
// Read folder
fd, err := os.OpenFile("D:/w_gopath/src/wei01/w_go_pg_tidb/05.go_wei", os.O_RDONLY, os.ModeDir)
defer fd.Close()
fdreader, err := fd.Readdir(-1)
for zixiang, info := range fdreader {
fmt.Println(zixiang, info.Name(), info.Size(), info.ModTime(), info.IsDir())
}
}
// Big file replication
func weicopy() {
f4, err := os.Open("wei.mp3")
if err != nil && err != io.EOF {
fmt.Println(" open mp3 Failure ")
}
defer f4.Close()
f5, err := os.Create("wei_2.mp3")
if err != nil && err != io.EOF {
fmt.Println(" open mp3 Failure ")
}
defer f5.Close()
buf4k := make([]byte, 4096)
for {
n, err := f4.Read(buf4k)
f5.Write(buf4k[:n])
if err != nil && err != io.EOF {
fmt.Println(" Error reading file ")
break
}
if n == 0 {
fmt.Println(" All the documents have been read ")
break
}
fmt.Println(n)
}
}
边栏推荐
- WPF 截图控件之绘制方框与椭圆(四) 「仿微信」
- Analysis of QT basic engineering
- DoD 和 DoR,消减「认知偏差」的两大神器
- Qt 之自定义界面(实现无边框、可移动)
- 暑假集训week1
- Determine whether the values of two objects are equal
- 一文搞懂什么是二叉树(二叉树的种类、遍历方式、定义)
- R language Monte Carlo method and average method are used to calculate the definite integral. Considering the random point casting method, the confidence is 0.05, and the requirement is ϵ= 0.01, numbe
- 如何使用“COPY –link”加速 Docker 构建和优化缓存
- Open source, compliance escort! 2022 open atom global open source summit open source compliance sub forum is about to open
猜你喜欢
Using Riemann sum to calculate approximate integral in R language
JVM知识点详细整理(长文警告)
8. Interleave - understand ThreadPoolExecutor thread pool from architecture design to practice
Lucky draw system with background source code
How to synchronize when the primary and sub warehouses are modified?
Pytorch 入门
ES6 arrow function this points to
Sunwenlong, Secretary General of the open atom open source foundation, worked together to expand open source
【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
One click blog building: how to use WordPress plug-in to build a dedicated blog
随机推荐
Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29
Alibaba architects spent a year sorting out the "Lucene advanced document", and you are also a big factory employee!
牛客网刷题
Niuke net brush questions
Package delivery (greedy)
Conference OA project - my approval
Kunlunbase instruction manual (II) best practices for peer-to-peer deployment
GPO: using PowerShell scripts in start/logon
Roots of equations in R language dichotomy and Newton iteration
『知识集锦』一文搞懂mysql索引!!(建议收藏)
QT's user-defined interface (borderless and movable)
Pyqt5 rapid development and practice 6.6 qformlayout & 6.7 nested layout & 6.8 qsplitter
如何在匹配行之前使用 grep 显示文件名和行号
深入理解C# 可空类型
Peking University open classes are coming! Welcome to the "AI for science" class
ES6-箭头函数this指向
开放原子开源基金会秘书长孙文龙 | 凝心聚力,共拓开源
LeetCode_416_分割等和子集
Luogu p1816 loyalty solution
带你浅聊一下PHP搭建的电商商城系统