IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Go语言相关 -> 正文阅读

[网络协议]Go语言相关

http 客户端,go 做性能测试的底层

郑东成? ?2021.12.15?

======my_http.go======
package my_package
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

func my_client() http.Client{
	proxyAddr := "http://127.0.0.1:8888/"
	proxy, err := url.Parse(proxyAddr)
	if err != nil {
		fmt.Println(err)
	}
	netTransport := &http.Transport{
		Proxy:                 http.ProxyURL(proxy),
		MaxIdleConnsPerHost:   10,
		ResponseHeaderTimeout: time.Second * time.Duration(5),
	}
	httpClient := http.Client{
		Timeout:   time.Second * 10,
		Transport: netTransport,
	}
	return httpClient
}

type my_http struct {
	Name		string	 `json:"Name"`
	Method      string   `json:"Method"`
	Url 		string   `json:"Url"`
	Params      map[string]string  	`json:"Params"`
	Request     map[string]string	`json:"Request"`
	Headers     map[string]string   `json:"Headers"`
}

func (this *my_http)full_path()string{
	params := url.Values{}
	for k, v := range this.Params {
		params.Set(k,v)
	}
	url1, err := url.Parse(this.Url)
	if err != nil{
		fmt.Println(err)
	}
	url1.RawQuery = params.Encode()
	urlPath := url1.String()
	return urlPath
}

func (this *my_http)to_string()(method,request string,headers map[string]string){
	method = this.Method
	Request_byte,err := json.Marshal(this.Request)
	if err != nil{
		fmt.Println(err)
	}
	request = string(Request_byte)
	return method,request,this.Headers
}

func (this *my_http)run_http(httpClient http.Client,method,url,request string,headers map[string]string) (body2 string, status_code int) {
	res, err := http.NewRequest(method, url, strings.NewReader(request))
	if err != nil {
		fmt.Println("ERR !",err)
	}
	for k,v := range headers{
		res.Header.Add(k, v)
	}
	resp, err := httpClient.Do(res)
	if err != nil{
		fmt.Println(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		fmt.Println(err)
	}
	body, _ := ioutil.ReadAll(resp.Body)
	body2 = string(body)
	status_code = resp.StatusCode
	return body2,status_code
}

func new_my_http(json_str string)my_http{
	my_http1 := my_http{}
	err := json.Unmarshal([]byte(json_str), &my_http1)
	if err != nil{
		fmt.Println(err)
	}
	return my_http1
}


func Run_http(json_str string)(int,string,int64) {
	//client := http.Client{}
	client := my_client()
	http1 := new_my_http(json_str)
	url := http1.full_path()
	method,request,headers := http1.to_string()
	start := time.Now()
	body,status_code := http1.run_http(client,method,url,request,headers)
	elapsed := time.Since(start).Nanoseconds()/int64(time.Millisecond)
	return status_code,body,elapsed
}

//func fang_mo_xing() {
//	//json_str := `{
//	//       "method": "POST",
//	//       "url": "http://192.168.1.148:9527/japi/base/consumer/auth/userLogin",
//	//       "params":{},
//	//       "request": {
//	//          "email": "Test0073@163.com",
//	//          "password": "7c4a8d09ca3762af61e59520943dc26494f8941b"
//	//                },
//	//       "headers":{
//	//			"Content-Type":"application/json;charset=utf-8",
//	//			"Authorization":"Bearer "
//	//			}
//	//       }`
//	json_str := `{"name": "企业基本信息", "method": "get", "ip": "192.168.1.148:9527", "url": "http://10.99.30.99:8020/japi/tax/collect/NotifyMessage/query?entId=ENT_202104270824031857214499&pageNo=1&viewed=0&pageSize=9999", "params": {}, "RequestBody": {},
//				"headers": {"Host": "192.168.1.148:9527", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0", "Accept": "*/*", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", "Accept-Encoding": "gzip, deflate"
//				, "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDIxMDQyNzA4MjQwMzAxMjg2NzQ0MjIiLCJleHAiOjE2MjA4OTkwNjEsInZlcnNpb24iOjg0fQ.3pgBOPd6O4tMOdev-ICisF1lKk_r91HDDdbQrucUIJ0"
//				, "sysCode": "HMSYS02", "pageName": "%E4%BC%81%E4%B8%9A%E5%9F%BA%E6%9C%AC%E4%BF%A1%E6%81%AF", "router": "/tax-data/preparation/basicsMsg", "Content-Type": "application/json;charset=utf-8", "Content-Length": "57", "Origin": "http://192.168.1.148:9527", "Connection": "keep-alive", "Referer": "http://192.168.1.148:9527/tax-data/preparation/basicsMsg", "Cookie": "TaxSaaS-1.0.0uuid=202103231128362060298547; TaxSaaS-1.0.0token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDIxMDMyMzExMjgzNjIwNjAyOTg1NDciLCJ1c2VyTmFtZSI6IuWNjuebnyIsImV4cCI6MTYxNzI3NjA5OSwidmVyc2lvbiI6MzA0fQ.M-4EUM_oHlhMoQitaRyMLL4xWiE54I03QIxGiyhCfMI"}}`
//
//	status_code,body,elapsed := Run_http(json_str)
//	fmt.Println(status_code,body,elapsed)
//}

===========my_json.go================

package my_package

import (
	"encoding/json"
	"strings"
)

//type my_http struct {
//	Method      string   `json:"Method"`
//	Url 		string   `json:"Url"`
//	Params      map[string]string  		  `json:"Params"`
//	Request     map[string]string   	  `json:"Request"`
//	Headers     map[string]string  		  `json:"Headers"`
//}

type my_api struct {
	My_http []my_http
}

func New_may_api(data string)my_api{
	api := my_api{}
	json.Unmarshal([]byte(data),&api.My_http)
	return api
}


func (this *my_api)Set_params(entId string){
	for _,http := range this.My_http{
		http.Params["entId"] = entId
	}
}

func (this *my_api)Set_request(old_entId,new_entId string){
	for _,http := range this.My_http{
		for k,v := range http.Request{
				http.Request[k] = strings.Replace(v,old_entId,new_entId,-1)
		}
	}
}

func (this *my_api)Set_headers(Authorization string){
	for _,http := range this.My_http{
		http.Headers["Authorization"] = Authorization
	}
}

func (this *my_api)Get_json(i int)string{
	ss,_ := json.Marshal(this.My_http[i])
	return string(ss)
}



//func main2() {
//
//	data := `[
//        {"name": "企业基本信息", "method": "GET", "ip": "192.168.1.148:9527", "url": "http://10.99.30.99:8020/tax-data/preparation/basicsMsg", "params": {"viewed": "0"}, "Request": {"entId": "ENT_202103231128360537097596", "viewed": "1"}, "headers": {"Host": "192.168.1.148:9527", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0", "Accept": "text/html,application/xhtml xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive", "Cookie": "TaxSaaS-1.0.0uuid=202103231128362060298547; TaxSaaS-1.0.0token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDIxMDMyMzExMjgzNjIwNjAyOTg1NDciLCJ1c2VyTmFtZSI6IuWNjuebnyIsImV4cCI6MTYxNzI3NjA5OSwidmVyc2lvbiI6MzA0fQ.M-4EUM_oHlhMoQitaRyMLL4xWiE54I03QIxGiyhCfMI", "Upgrade-Insecure-Requests": "1", "If-Modified-Since": "Wed, 31 Mar 2021 13:03:17 GMT", "If-None-Match": "60647315-24f"}}
//		,{"name": "企业基本信息", "method": "GET", "ip": "192.168.1.148:9527", "url": "http://10.99.30.99:8020/collect/NotifyMessage/queryMessageCount", "params": {"entId": "ENT_202103231128360537097596"}, "Request": {"entId": "ENT_202103231128360537097596", "viewed": "1"}, "headers": {"Host": "192.168.1.148:9527", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0", "Accept": "*/*", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", "Accept-Encoding": "gzip, deflate", "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDIxMDMyMzExMjgzNjIwNjAyOTg1NDciLCJ1c2VyTmFtZSI6IuWNjuebnyIsImV4cCI6MTYxNzI3NjA5OSwidmVyc2lvbiI6MzA0fQ.M-4EUM_oHlhMoQitaRyMLL4xWiE54I03QIxGiyhCfMI", "sysCode": "HMSYS02", "pageName": "%E4%BC%81%E4%B8%9A%E5%9F%BA%E6%9C%AC%E4%BF%A1%E6%81%AF", "router": "/tax-data/preparation/basicsMsg", "Connection": "keep-alive", "Referer": "http://192.168.1.148:9527/tax-data/preparation/basicsMsg", "Cookie": "TaxSaaS-1.0.0uuid=202103231128362060298547; TaxSaaS-1.0.0token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDIxMDMyMzExMjgzNjIwNjAyOTg1NDciLCJ1c2VyTmFtZSI6IuWNjuebnyIsImV4cCI6MTYxNzI3NjA5OSwidmVyc2lvbiI6MzA0fQ.M-4EUM_oHlhMoQitaRyMLL4xWiE54I03QIxGiyhCfMI"}}
//		]`
//
//	Api := New_may_api(data)
//	old_entId := "ENT_202103231128360537097596"
//	new_entId := "ENT_00000000"
//	headers := "Bearer 111111111111"
//	Api.Set_params(new_entId)
//	Api.Set_request(old_entId,new_entId)
//	Api.Set_headers(headers)
//
//	for i,_ := range Api.My_http{
//		js := Api.Get_json(i)
//		fmt.Println(js)
//	}
//
//}

go?语言的浏览器录制脚本

郑东成? 2021.12.23

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"sync"
)

func Writer(w http.ResponseWriter, resp *http.Response) {
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	for i, j := range resp.Header {
		for _, k := range j {
			w.Header().Add(i, k)
		}
	}
	for _, c := range resp.Cookies() {
		w.Header().Add("Set-Cookie", c.Raw)
	}
	_, ok := resp.Header["Content-Length"]
	if !ok && resp.ContentLength > 0 {
		w.Header().Add("Content-Length", fmt.Sprint(resp.ContentLength))
	} else {
	}
	w.WriteHeader(resp.StatusCode)
	w.Write(data)

}

func get_body(Body *io.ReadCloser) string {
	bodyBytes, _ := ioutil.ReadAll(*Body)
	bodyStr := string(bodyBytes)
	*Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
	return bodyStr
}

func writer_file(log string) {
	os.MkdirAll("D:/Program Files/郑东成", os.ModePerm)
	f, err := os.OpenFile("D:/Program Files/郑东成/hello_lin", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	defer f.Close()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		f.Write([]byte(log))
	}
}

func get_resp(r *http.Request, body string) {
	mutex.Lock()
	Method := fmt.Sprintf("Method: %s\r\n", r.Method)
	URL := fmt.Sprintf("URL: %s\r\n", r.URL)
	Header := fmt.Sprintf(`Header: {"Content-Type":"%s","Syscode":"%s","Authorization":"%s"}`+"\r\n", r.Header.Values("Content-Type"), r.Header.Values("Syscode"), r.Header.Values("Authorization"))
	Body := fmt.Sprintf("Body: %s\r\n\r\n", body)
	writer_file(Method)
	writer_file(URL)
	writer_file(Header)
	writer_file(Body)
	mutex.Unlock()
}

func handler(w http.ResponseWriter, r *http.Request) {

	r.RequestURI = ""
	req_body := get_body(&r.Body)
	get_resp(r, req_body)

	resp, err := http.DefaultClient.Do(r)
	get_body(&resp.Body)
	// fmt.Println(res_body)

	if err != nil {
		http.NotFound(w, r)
		return
	}
	Writer(w, resp)

}

var mutex sync.Mutex

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8888", nil)
	os.Exit(0)
}

go?的文件读写

郑东成 2021.12.24

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
)

type My_file struct {
	Path      string
	Full_path string
}

func (f *My_file) Get_Full_Path() {
	Getwd, _ := os.Getwd()
	f.Full_path = filepath.ToSlash(Getwd + f.Path)
}

func (f *My_file) Read() {
	f.Full_path = filepath.ToSlash(f.Full_path)
	content, err := ioutil.ReadFile(f.Full_path)
	if err != nil {
		fmt.Println("err", err)
	}
	contents := string(content)
	fmt.Println(contents)
}

func (f *My_file) Write_String_Line(write string) {
	f.Full_path = filepath.ToSlash(f.Full_path)
	path, _ := path.Split(f.Full_path)
	fmt.Println(path)

	os.MkdirAll(path, os.ModePerm)
	file_, err := os.OpenFile(f.Full_path, os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		fmt.Println("err", err)
	}
	file_.WriteString(write + "\r\n")
	file_.Close()
}

func (f *My_file) Write_String_Slices(write []string) {
	for _, value := range write {
		f.Write_String_Line(value)
	}
}

func main() {
	f1 := My_file{}
	// f1.Path = "/log/log.txt"
	// f1.Get_Full_Path()
	f1.Full_path = `D:\GoProject2\poject\pp2\main\log\log.txt`
	// f1.Write_String_Line("hello")
	// f1.Write_String_Slices([]string{"hello", "word"})
	f1.Read()
}

go?语言操作excel 源码

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"strings"

	"github.com/xuri/excelize/v2"
)

func check(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

type Excel_Read struct {
	Excel
	Excel_name string `json:"Excel_name"`
	Sheet_name string `json:"Sheet_name"`
}

func (e *Excel_Read) Init(json_str string) {
	b := []byte(json_str)
	json.Unmarshal(b, e)
}

func (e *Excel_Read) Read() {
	e.Open(e.Excel_name)
	Rows := e.GetRows(e.Sheet_name)
	fmt.Println(Rows)
}

type Excel_Write struct {
	Excel
	Excel_name   string            `json:"Excel_name"`
	Sheet_name   string            `json:"Sheet_name"`
	Write_string map[string]string `json:"Write_string"`
}

func (e *Excel_Write) Init(json_str string) {
	b := []byte(json_str)
	json.Unmarshal(b, e)
}

func (e *Excel_Write) Write() {
	e.Open(e.Excel_name)
	e.SetCellValues(e.Sheet_name, e.Write_string)
	e.Save(e.Excel_name)
}

type Excel_Create struct {
	Excel
	Excel_name string `json:"Excel_name"`
}

func (e *Excel_Create) Init(json_str string) {
	b := []byte(json_str)
	json.Unmarshal(b, e)
}

func (e *Excel_Create) Creat() {
	e.Create()
	e.Save(e.Excel_name)
}

type Excel struct {
	file *excelize.File
}

func (e *Excel) Create() {
	file := excelize.NewFile()
	e.file = file
}

func (e *Excel) Save(Excel_name string) {
	err := e.file.SaveAs(Excel_name + ".xlsx")
	check(err)
}

func (e *Excel) Open(Excel_name string) {
	file, err := excelize.OpenFile(Excel_name + ".xlsx")
	check(err)
	e.file = file
}

func (e *Excel) GetRows(Sheet_name string) [][]string {
	rows, err := e.file.GetRows(Sheet_name)
	check(err)
	return rows
}

func (e *Excel) PrintRows(Rows [][]string) {
	for _, row := range Rows {
		for _, colCell := range row {
			fmt.Print(colCell, "\t\t\t")
		}
		fmt.Println()
	}
}

func (e *Excel) SetCellValues(Sheet_name string, Rows map[string]string) {
	for k, v := range Rows {
		e.file.SetCellValue(Sheet_name, k, v)
	}
}

var (
	Open    string
	Funtion string
	Data    string
)

func main() {

	flag.StringVar(&Data, "C", "", "数据_json")
	flag.StringVar(&Funtion, "F", "", "函数名_read/write")
	flag.StringVar(&Data, "D", "", "数据_json")
	flag.Parse()

	Data = strings.Replace(Data, `'`, `"`, -1)

	switch Funtion {

	case "create":
		create := Excel_Create{}
		create.Init(Data)
		create.Creat()
	case "write":
		write := Excel_Write{}
		write.Init(Data)
		write.Write()
	case "read":
		read := Excel_Read{}
		read.Init(Data)
		read.Read()
	default:
		fmt.Println("查无此命令")
	}

}

?python调用和cmd调用的语法

#coding:utf-8
import os

if __name__ == '__main__':
    cmd = """
    excel.exe -F "create" -D "{'Excel_name':'my_excel'}"
    """
    cmd = """
    excel.exe -F "write" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1','Write_string':{'B1':'Apple', 'C1': 'Orange', 'D1': 'Pear','A2': 'Small', 'A3': 'Normal', 'A4': 'Large'}}"
    """
    cmd = """
    excel.exe -F "read" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1'}"
    """
    os.system(cmd)


# cmd
# excel.exe -F "create" -D "{'Excel_name':'my_excel'}"
# excel.exe -F "read" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1'}"
# excel.exe -F "write" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1','Write_string':{'B1':'Apple', 'C1': 'Orange', 'D1': 'Pear','A2': 'Small', 'A3': 'Normal', 'A4': 'Large'}}"

?go?python?excel的结合使用

?

#coding:utf-8
import subprocess

if __name__ == '__main__':

    cmd1 = """excel.exe -F "create" -D "{'Excel_name':'my_excel'}"""
    cmd2 = """excel.exe -F "write" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1','Write_string':{'B1':1, 'C1': 2, 'D1': 3,'A2': 'Small', 'A3': 'Normal', 'A4': 'Large'}}"""
    cmd3 = """excel.exe -F "read" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1'}"""

    ps = subprocess.Popen(cmd3, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    while True:
        data = ps.stdout.readline().decode('utf-8')
        break

    print(data)

# cmd
# excel.exe -F "create" -D "{'Excel_name':'my_excel'}"
# excel.exe -F "read" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1'}"
# excel.exe -F "write" -D "{'Excel_name':'my_excel','Sheet_name':'Sheet1','Write_string':{'B1':'Apple', 'C1': 'Orange', 'D1': 'Pear','A2': 'Small', 'A3': 'Normal', 'A4': 'Large'}}"

?更新后的?go

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"strings"

	"github.com/xuri/excelize/v2"
)

func check(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

type Excel_Read struct {
	Excel
	Excel_name string `json:"Excel_name"`
	Sheet_name string `json:"Sheet_name"`
}

func (e *Excel_Read) Init(json_str string) {
	b := []byte(json_str)
	json.Unmarshal(b, e)
}

func (e *Excel_Read) Read() string {
	e.Open(e.Excel_name)
	Rows := e.GetRows(e.Sheet_name)
	str, err := json.Marshal(Rows)
	if err != nil {
		fmt.Println(err)
	}
	return string(str)
}

type Excel_Write struct {
	Excel
	Excel_name   string                 `json:"Excel_name"`
	Sheet_name   string                 `json:"Sheet_name"`
	Write_string map[string]interface{} `json:"Write_string"`
}

func (e *Excel_Write) Init(json_str string) {
	b := []byte(json_str)
	json.Unmarshal(b, e)
}

func (e *Excel_Write) Write() {
	e.Open(e.Excel_name)
	e.SetCellValues(e.Sheet_name, e.Write_string)
	e.Save(e.Excel_name)
}

type Excel_Create struct {
	Excel
	Excel_name string `json:"Excel_name"`
}

func (e *Excel_Create) Init(json_str string) {
	b := []byte(json_str)
	json.Unmarshal(b, e)
}

func (e *Excel_Create) Creat() {
	e.Create()
	e.Save(e.Excel_name)
}

type Excel struct {
	file *excelize.File
}

func (e *Excel) Create() {
	file := excelize.NewFile()
	e.file = file
}

func (e *Excel) Save(Excel_name string) {
	err := e.file.SaveAs(Excel_name + ".xlsx")
	check(err)
}

func (e *Excel) Open(Excel_name string) {
	file, err := excelize.OpenFile(Excel_name + ".xlsx")
	check(err)
	e.file = file
}

func (e *Excel) GetRows(Sheet_name string) [][]string {
	rows, err := e.file.GetRows(Sheet_name)
	check(err)
	return rows
}

func (e *Excel) PrintRows(Rows [][]string) {
	for _, row := range Rows {
		for _, colCell := range row {
			fmt.Print(colCell, "\t\t\t")
		}
		fmt.Println()
	}
}

func (e *Excel) SetCellValues(Sheet_name string, Rows map[string]interface{}) {
	for k, v := range Rows {
		e.file.SetCellValue(Sheet_name, k, v)
	}
}

var (
	Open    string
	Funtion string
	Data    string
)

func main() {

	flag.StringVar(&Data, "C", "", "数据_json")
	flag.StringVar(&Funtion, "F", "", "函数名_read/write")
	flag.StringVar(&Data, "D", "", "数据_json")
	flag.Parse()

	Data = strings.Replace(Data, `'`, `"`, -1)

	switch Funtion {

	case "create":
		create := Excel_Create{}
		create.Init(Data)
		create.Creat()
	case "write":
		write := Excel_Write{}
		write.Init(Data)
		write.Write()
	case "read":
		read := Excel_Read{}
		read.Init(Data)
		res := read.Read()
		// bres := []byte(res)
		fmt.Println(res)

	default:
		fmt.Println("查无此命令")
	}
}

?golang?的?mysql

package main

import (
	"database/sql"
	"encoding/json"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

type My_Sql struct {
	Db *sql.DB
}

func (my *My_Sql) Init(USER_NAME, PASS_WORD, HOST, PORT, DataBase string) {
	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", USER_NAME, PASS_WORD, HOST, PORT, DataBase)
	MysqlDb, err := sql.Open("mysql", dbDSN)
	if err != nil {
		fmt.Println("数据源配置不正确: ", err)
	}
	if err = MysqlDb.Ping(); nil != err {
		fmt.Println("数据库链接失败: ", err)
	}
	my.Db = MysqlDb
}

func (my *My_Sql) Close() {
	my.Db.Close()
}

func (my *My_Sql) Select(Query string) {
	rows, err := my.Db.Query(Query)
	defer rows.Close()
	if err != nil {
		fmt.Printf("查询错误:%v", err)
		return
	}
	// 创建返回表
	table := [][]string{}
	columns, _ := rows.Columns()
	// 插入表头
	table = append(table, columns)
	// 创建被 Scan 的容器
	values := make([]sql.RawBytes, len(columns))
	scanArgs := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	// Scan
	for rows.Next() {
		rows.Scan(scanArgs...)
		line := []string{}
		// Scan 一行数据 往返回表添加一行数据
		for i := 0; i < len(columns); i++ {
			line = append(line, string(values[i]))
		}
		table = append(table, line)
	}
	str, err := json.Marshal(table)
	fmt.Println(string(str))
}

func (my *My_Sql) Execute(Query string) {
	_, err := my.Db.Exec(Query)
	if err != nil {
		fmt.Println("Execute:", err)
	}

}

func main() {
	SELECT := ` SELECT a100000_n49 FROM hmtax.a100000 limit 3 ;`
	UPDATE := ` UPDATE hmtax.a100000 SET tax_year="2011" WHERE ent_id="ENT_201211151555485791996685270" and tax_year="2012"; `
	INSERT := ` INSERT INTO hmtax.a100000(ent_id,tax_year) VALUES ("ENT_201211151555485791996685270","2012");`
	Delete := ` Delete FROM hmtax.a100000 Where ent_id="ENT_201211151555485791996685270" ;`

	my_sql := My_Sql{}
	my_sql.Init("账号", "密码", "ip", "端口", "数据库实例名")
	my_sql.Select(SELECT)
	my_sql.Execute(UPDATE)
	my_sql.Execute(INSERT)
	my_sql.Execute(Delete)
	my_sql.Close()

}

golang?mysql?的完善

package main

import (
	"database/sql"
	"encoding/json"
	"flag"
	"fmt"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

type My_Sql struct {
	Db *sql.DB
}

func (my *My_Sql) Init(USER_NAME, PASS_WORD, HOST, PORT, DataBase string) {
	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", USER_NAME, PASS_WORD, HOST, PORT, DataBase)
	MysqlDb, err := sql.Open("mysql", dbDSN)
	if err != nil {
		fmt.Println("数据源配置不正确: ", err)
	}
	if err = MysqlDb.Ping(); nil != err {
		fmt.Println("数据库链接失败: ", err)
	}
	my.Db = MysqlDb
}

func (my *My_Sql) Close() {
	my.Db.Close()
}

func (my *My_Sql) Select(Query string) {
	rows, err := my.Db.Query(Query)
	defer my.Db.Close()
	defer rows.Close()
	if err != nil {
		fmt.Printf("查询错误:%v", err)
		return
	}
	// 创建返回表
	table := [][]string{}
	columns, _ := rows.Columns()
	// 插入表头
	table = append(table, columns)
	// 创建被 Scan 的容器
	values := make([]sql.RawBytes, len(columns))
	scanArgs := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	// Scan
	for rows.Next() {
		rows.Scan(scanArgs...)
		line := []string{}
		// Scan 一行数据 往返回表添加一行数据
		for i := 0; i < len(columns); i++ {
			line = append(line, string(values[i]))
		}
		table = append(table, line)
	}
	str, err := json.Marshal(table)
	fmt.Println(string(str))
}

func (my *My_Sql) Execute(Query string) {
	defer my.Db.Close()
	_, err := my.Db.Exec(Query)
	if err != nil {
		fmt.Println("Execute:", err)
	}

}

var (
	Funtion string
	Data    string
	Sql     string
)

type Connet struct {
	USER_NAME string `json:"USER_NAME"`
	PASS_WORD string `json:"PASS_WORD"`
	HOST      string `json:"HOST"`
	PORT      string `json:"PORT"`
	DataBase  string `json:"DataBase"`
}

func main() {

	flag.StringVar(&Funtion, "F", "", "函数名_select/execute")
	flag.StringVar(&Data, "D", "", "数据库连接串")
	flag.StringVar(&Sql, "S", "", " sql")
	flag.Parse()

	Data = strings.Replace(Data, `'`, `"`, -1)

	switch Funtion {

	case "select":
		c := Connet{}
		err := json.Unmarshal([]byte(Data), &c)
		if err != nil {
			fmt.Println(err)
		}
		my_Sql := My_Sql{}
		my_Sql.Init(c.USER_NAME, c.PASS_WORD, c.HOST, c.PORT, c.DataBase)
		my_Sql.Select(Sql)
		break

	case "execute":
		c := Connet{}
		err := json.Unmarshal([]byte(Data), &c)
		if err != nil {
			fmt.Println(err)
		}
		my_Sql := My_Sql{}
		my_Sql.Init(c.USER_NAME, c.PASS_WORD, c.HOST, c.PORT, c.DataBase)
		my_Sql.Execute(Sql)
		break
	default:
		fmt.Println("查无此命令")
		break
	}

	// ./main.exe -F "select" -D "{'HOST': '192.168.1.158', 'USER_NAME': 'root', 'PASS_WORD': 'Admin@9900', 'DataBase': 'hmtax','PORT': '3306'}" -S "SELECT a100000_n49 FROM hmtax.a100000 limit 3 ;"
	// ./main.exe -F "execute" -D "{'HOST': '192.168.1.158', 'USER_NAME': 'root', 'PASS_WORD': 'Admin@9900', 'DataBase': 'hmtax','PORT': '3306'}" -S "UPDATE hmtax.a100000 SET tax_year='2011' WHERE ent_id='ENT_201211151555485791996685270' and tax_year='2012'; "
	// ./main.exe -F "execute" -D "{'HOST': '192.168.1.158', 'USER_NAME': 'root', 'PASS_WORD': 'Admin@9900', 'DataBase': 'hmtax','PORT': '3306'}" -S "INSERT INTO hmtax.a100000(ent_id,tax_year) VALUES ('ENT_201211151555485791996685270','2012');"

}

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-01-24 11:18:35  更:2022-01-24 11:20:35 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 10:42:30-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码