内存中变成可存储或传输的过程称之为序列化(dict,split,struct转string)
package main
import (
"encoding/json"
"fmt"
)
type Stu struct {
Name string
Age int
}
func JsonDump() (ret string, err error) {
stu1 := Stu{
Name: "somebody",
Age: 20,
}
data, err := json.Marshal(stu1)
if err != nil {
err = fmt.Errorf("json dump failed:", err)
return
}
ret = string(data)
fmt.Println(ret)
return
}
func main() {
JsonDump()
}
磁盘读取到内存
需要先定义一个存储的数据类型(map struct),string要转成byte
package main
import (
"encoding/json"
"fmt"
)
type Stu struct {
Name string
Age int
}
func JsonDump() (ret string, err error) {
stu1 := Stu{
Name: "somebody",
Age: 20,
}
data, err := json.Marshal(stu1)
if err != nil {
err = fmt.Errorf("json dump failed:", err)
return
}
ret = string(data)
return
}
func JsonLoad(res string) (ret interface{}, err error) {
var stu Stu
err = json.Unmarshal([]byte(res), &stu)
if err != nil {
err = fmt.Errorf("json loads failed:", err)
return
}
ret = stu
return
}
func main() {
response, _ := JsonDump()
res, _ := JsonLoad(response)
fmt.Println(res)
}
flag模块
package main
import (
"flag"
"fmt"
)
func main() {
var confPath string
var command string
var port int
flag.StringVar(&confPath, "c", "conf", "conf file of app")//变量名 -c 默认值 描述
flag.StringVar(&command, "a", "online", "command to execute")
flag.IntVar(&port, "p", 10000, "port of service")
flag.Parse()
fmt.Println(confPath)
fmt.Println(command)
fmt.Println(port)
}
slice取随机数
var indexList \[\]int
for i := 0; i < chooseNum; i++ {
//避免随机出现重复
for {
randIndex := rand.Intn(len(totalList))
flag := true
for \_, v := range indexList {
if v == randIndex {
flag = false
}
}
if flag {
indexList = append(indexList, randIndex)
break
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"time"
"golang.org/x/crypto/ssh"
)
func connect(user, password, host, key string, port int) (*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)
if key == "" {
auth = append(auth, ssh.Password(password))
} else {
pemBytes, err := ioutil.ReadFile(key)
if err != nil {
return nil, err
}
var singer ssh.Signer
if password == "" {
singer, err = ssh.ParsePrivateKey(pemBytes)
} else {
singer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password))
}
if err != nil {
return nil, err
}
auth = append(auth, ssh.PublicKeys(singer))
}
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 3 \* time.Second,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
// connet to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
// create session
if session, err = client.NewSession(); err != nil {
return nil, err
}
return session, nil
}
func main() {
session, err := connect("admin", "", "172.20.165.161", "/home/admin/id_rsa", 22)
if err != nil {
fmt.Println(err)
}
defer session.Close()
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Run("sh /export/Packages/merger\_server\_ab/latest/bin/stop.sh")
}
阻塞方式(需要执行结果)
//阻塞式的执行外部shell命令的函数,等待执行完毕并返回标准输出
func exec_shell(s string) (string, error){
//函数返回一个*Cmd,用于使用给出的参数执行name指定的程序
cmd := exec.Command("/bin/bash", "-c", s)
//读取io.Writer类型的cmd.Stdout,再通过bytes.Buffer(缓冲byte类型的缓冲器)将byte类型转化为string类型(out.String():这是bytes类型提供的接口)
var out bytes.Buffer
cmd.Stdout = &out
//Run执行c包含的命令,并阻塞直到完成。 这里stdout被取出,cmd.Wait()无法正确获取stdin,stdout,stderr,则阻塞在那了
err := cmd.Run()
checkErr(err)
return out.String(), err
}
shell标准输出逐行实时处理
func execCommand(commandName string, params []string) bool {
//函数返回一个*Cmd,用于使用给出的参数执行name指定的程序
cmd := exec.Command("/bin/bash","-c",command)
//显示运行的命令
fmt.Println(cmd.Args)
//StdoutPipe方法返回一个在命令Start后与命令标准输出关联的管道。Wait方法获知命令结束后会关闭这个管道,一般不需要显式的关闭该管道。
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println(err)
return false
}
cmd.Start()
//创建一个流来读取管道内内容,这里逻辑是通过一行一行的读取的
reader := bufio.NewReader(stdout)
//实时循环读取输出流中的一行内容
for {
line, err2 := reader.ReadString('\\n')
if err2 != nil || io.EOF == err2 {
break
}
fmt.Println(line)
}
//阻塞直到该命令执行完成,该命令必须是被Start方法开始执行的
cmd.Wait()
return true
}
读文件
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
inputFile, err := os.Open("ip.txt")
if err != nil {
err = errors.New("open file error")
fmt.Println(err)
return
}
defer inputFile.Close()
fd, err := ioutil.ReadAll(inputFile)
fmt.Println(string(fd))
}
写文件
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
outputFile, outputError := os.OpenFile("ip.txt", os.O_WRONLY|os.O_CREATE, 0666)
if outputError != nil {
fmt.Println(outputError)
return
}
defer outputFile.Close()
outputWriter := bufio.NewWriter(outputFile)
outputString := "3.3.3.3\n"
for i := 0; i < 10000; i++ {
outputWriter.WriteString(outputString)
}
outputWriter.Flush()
}
package main
import (
"fmt"
)
func tryRecover() {
defer func() {
r := recover()
if err, ok := r.(error); ok {
fmt.Println("error occurred:", err)
} else {
panic(r)
}
}()
a := 5
b := 0
c := a / b
fmt.Println(c)
}
func main() {
tryRecover()
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章