This is a creation in Article, where the information may have evolved or changed.
So, how do I insert a directory? Not [TOC]?
Command-line arguments
import "flag"func main() {ports := flag.String("ports", "10086", "list the port ....")var version_check boolflag.BoolVar(&version_check, "v", false, "version")flag.Parse()if version_check {do()}portsList := strings.Split(*ports, ",")if len(portsList) > 5 {fmt.Println("no more than 5 ports")return}}
Configuration file
package mainimport ("fmt""github.com/BurntSushi/toml")type tomlConfig struct {TitlestringMysqlmysqlInfo}type mysqlInfo struct {HoststringPortintUserstringPasswdstringDbstring}func main() {var config tomlConfigif _, err := toml.DecodeFile("config.toml", &config); err != nil {fmt.Println(err)return}fmt.Println(config.Title)fmt.Println(config.Mysql.Host)}
The configuration file is as follows and requires the same name as in Tomlconfig, with the first letter capitalized in the code, lowercase in the configuration
Title = "test"[mysql]host = "11.22.33.44"port = 3306user = "smart"passwd = "smart"db = "smart"
Mysql
package mainimport ("database/sql""fmt"_ "github.com/go-sql-driver/mysql")func fetchdata() {db, err := sql.Open("mysql", "user:passwd@tcp(host:port)/database")if err != nil {fmt.Println(err)}err = db.Ping()if err != nil {fmt.Println(err)}rows, err := db.Query("select * from table")if err != nil {fmt.Println(err)}for rows.Next() {var counts stringvar indexs intif err := rows.Scan(&counts, &indexs); err != nil {fmt.Println(err)}fmt.Println(counts, indexs)}defer db.Close()}func main() {fetchdata()}
Socket
Func udpreceiver (port string) {defer workexitlock.done () var addr *net. Udpaddrvar server *net. Udpconnvar err Errorif addr, err = net. RESOLVEUDPADDR ("UDP", port); Err! = Nil {error.printf ("UDP Listener Error:%s", err) return}if server, err = net. LISTENUDP ("UDP", addr); Err! = Nil {error.printf ("UDP Listener Error:%s", err) return}if err = server. Setreadbuffer (Udp_read_buff); Err! = Nil {error.printf ("UDP Listener Error:%s", err) return}info.printf ("Listen UDP sucessfully, Port:%s", Port) var buf []bytefor {if Len (BUF) < udp_pack_size {buf = make ([]byte, Pack_buf_size, pack_buf_size)}nbytes, addr, err: = SERVER.R EADFROMUDP (BUF) if err! = Nil {error.printf ("Receive UDP data Error:%s", err) continue}msg: = Buf[:nbytes]buf = buf[nbytes: ]udpchan <-udpmessage{addr, MSG}}}//optional UDP or Tcpfunc Netsender (typename string, addr string, Retry int) {for {conn, er r: = Net. Dial (typename, addr) if err! = Nil {error.printf ("Make conn Error:", err) time. Sleep (time. Duration (Retry) * time. Second) Continue}for One: = Range Reschan {_, err = conn. Write ([]byte (one)) if err! = Nil {error.printf ("Send data Error:%s", err) Conn. Close () Break}}}}
In an experimental environment, if the peer does not process the data for the specified port, an ICMP packet prompt will be returned every second udp port distinct unreachable
, at which point the sender will have a corresponding send failure prompt, and one per second
Log
package mainimport ("config""io""log""os")var (Info *log.LoggerError *log.Logger)func Init(infoHandle io.Writer,errorHandle io.Writer) {Info = log.New(infoHandle,"INFO: ",log.Ldate|log.Ltime|log.Lshortfile)Error = log.New(errorHandle,"ERROR: ",log.Ldate|log.Ltime|log.Lshortfile)}func logInit(conf config.ProcessInfo) {pinfo := conf.Logdir + "/" + "log.info"perro := conf.Logdir + "/" + "log.err"finfo, err := os.OpenFile(pinfo, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)if err != nil {log.Fatalf("file open error : %v", err)}ferro, err := os.OpenFile(perro, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)if err != nil {log.Fatalf("file open error : %v", err)}Init(finfo, ferro)} func main() {gomaxprocs := runtime.NumCPU() - 1runtime.GOMAXPROCS(gomaxprocs)Info.Printf("Program start. GOMAXPROCS: %d", gomaxprocs)}
Synchronization statistics
Use sync/atomic
, the functions implemented by it can be used to achieve conflict-free statistics
import "sync/atomic"type count64 uint64func (c *count64) increment(incr int) count64 {return count64(atomic.AddUint64((*uint64)(c), uint64(incr)))}func (c *count64) get() count64 {return count64(atomic.LoadUint64((*uint64)(c)))}
Other
Note Some of the formatting requirements that are unique to Golang, such as:
- Cannot have useless variables, useless import
- Externally provided functions, the initial letter must be capitalized, otherwise it cannot be used by other package. Direct use of functions and global variables of different files in the same package
- Use as few exceptions as possible, judge and process by returning err, panic use when critical