package singleton
type Singleton interface {
AddOne() int
}
type singleton struct {
count int
}
var instance *singleton
func GetInstance() Singleton {
if instance == nil {
instance = new(singleton)
}
return instance
}
func (s *singleton) AddOne() int {
s.count++
return s.count
}
package singleton
import "testing"
func TestGetInstance(t *testing.T) {
counter1 := GetInstance()
if counter1 == nil {
t.Error("expected pointer to Singleton after calling GetInstance(), not nil")
}
expectedCounter := counter1
currentCount := counter1.AddOne()
if currentCount != 1 {
t.Errorf("After calling for the first time to count, count must be 1 but it is %d\n", currentCount)
}
counter2 := GetInstance()
if counter2 != expectedCounter {
t.Error("Expected same instance in counter2 but it got an different instance")
}
currentCount = counter2.AddOne()
if currentCount != 2 {
t.Errorf("After calling 'addone' using the second counter, the current count must be 2 but it is %d\n", currentCount)
}
}
package main
import (
"fmt"
)
func f(p string) {
fmt.Println("func f parameter:", p)
}
func g(p string) {
fmt.Println("func g parameter:", p)
}
func h(p string, q int) {
fmt.Println("func h parameter:", p, q)
}
func main() {
m := map[int]func(string){}
m[1] = f
m[2] = g
for k, v := range m {
fmt.Printf("%d:", k)
v("test")
}
d := map[string]interface{}{
"f": f,
"g": g,
"h": h,
}
for k, v := range d {
switch k {
case "f":
v.(func(string))("astring")
case "g":
v.(func(string))("gString")
case "h":
v.(func(string, int))("hString", 42)
}
}
}
package main
import (
"crypto/md5"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"time"
)
const PROGRAM_NAME = "genMd5.exe"
const RESULT_NAME = "md5result.txt"
func isDir(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
fmt.Println("os.Stat failed", err.Error())
return false
}
return fileInfo.IsDir()
}
func genMd5File(path string) []byte {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
log.Fatal(err)
}
fileMd5 := h.Sum(nil)
//fmt.Printf("%x\n", fileMd5)
return fileMd5
}
func getCurrentPath() (RelativePath string, AbsolutePath string, err error) {
RelativePath = filepath.Dir(os.Args[0])
file, _ := exec.LookPath(os.Args[0])
ApplicationPath, _ := filepath.Abs(file)
AbsolutePath, _ = filepath.Split(ApplicationPath)
return
}
var writeToFile = flag.Bool("writeToFile", false, "Write md5 result to file.")
func main() {
//fmt.Println(os.Args[0])
//fmt.Println(getCurrentPath())
//genMd5File("U3DXueZhanDaoDi.dll")
flag.Parse()
var f *os.File
var err error
if *writeToFile {
f, err = os.OpenFile(RESULT_NAME, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
f.WriteString(time.Now().String())
f.WriteString("\r\n")
}
relativePath, absolutePaht, _ := getCurrentPath()
fmt.Println(relativePath, absolutePaht)
dir, err := os.Open(absolutePaht)
if err != nil {
fmt.Println("os.Open failed", err.Error())
return
}
defer dir.Close()
names, err := dir.Readdirnames(-1)
if err != nil {
fmt.Println("dir.Readdirnames failed", err.Error())
return
}
for _, name := range names {
sub := absolutePaht + "\\" + name
if isDir(sub) {
continue
}
if name == PROGRAM_NAME {
continue
}
if name == RESULT_NAME {
continue
}
fileMd5 := genMd5File(sub)
str := fmt.Sprintf("%s:%x\r\n", name, fileMd5)
if *writeToFile {
f.WriteString(str)
} else {
fmt.Printf("%s:%x\n", name, fileMd5)
}
}
if !*writeToFile {
var done int
fmt.Scanf("%d", done)
}
}
package main
import (
"fmt"
"io"
"net"
"os"
)
func server() {
ln, err := net.Listen("tcp", ":9999")
if err != nil {
fmt.Println(err)
return
}
for {
c, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleServerConnection(c)
}
}
func handleServerConnection(c net.Conn) {
f, err := os.OpenFile("./test/aa.pdf", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, c)
fmt.Println("server copy end")
c.Close()
}
func client() {
c, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(err)
return
}
fileName := "test.pdf"
f, err := os.Open(fileName)
if err != nil {
fmt.Println("err opening file")
return
}
fileInfo, err := os.Lstat(fileName)
if err != nil {
fmt.Println("err Lstat")
return
}
fmt.Println(fileInfo.Size())
written, err := io.CopyN(c, f, fileInfo.Size())
if written != fileInfo.Size() || err != nil {
fmt.Println("error copy")
return
}
fmt.Println("client copy end", written)
c.Close()
}
func main() {
go server()
go client()
var input string
fmt.Scanln(&input)
}
package main
import (
"bufio"
"fmt"
"jian/tcp/tools"
"net"
"os"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "localhost:3333")
if err != nil {
fmt.Println("Error dialing", err.Error())
return
}
inputReader := bufio.NewReader(os.Stdin)
for {
input, _ := inputReader.ReadString('\n')
trimmedInput := strings.Trim(input, "\r\n")
if trimmedInput == "Q" {
return
}
b, err := tools.PackToJSON(1, []byte(trimmedInput))
if err != nil {
return
}
tools.Write(conn, string(b))
}
}
package main
import (
"fmt"
"jian/tcp/tools"
"net"
"os"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "3333"
CONN_TYPE = "tcp"
BUF_SIZE = 4 * 1024
)
func main() {
l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
if err != nil {
fmt.Println("listen failed:", err.Error())
os.Exit(1)
}
defer l.Close()
fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("accept failed:", err.Error())
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
defer conn.Close()
for {
msg, msgLen, err := tools.Read(conn)
if err != nil {
fmt.Println("Read failed.", err.Error())
return
}
fmt.Println("msg and msgLen", msg, msgLen)
msgtype, data, err := tools.UnpackJSON(msg)
if err != nil {
fmt.Println("UnpackJSON failed.", err.Error())
return
}
fmt.Println("msgtype and data", msgtype, data)
}
}
package tools
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"net"
"strings"
)
/*
Msg message struct
*/
type Msg struct {
Msgtype int
Data []byte
}
/*
PackToJSON create json string.
*/
func PackToJSON(msgtype int, data []byte) ([]byte, error) {
msgBag := &Msg{}
msgBag.Msgtype = msgtype
msgBag.Data = data
b, err := json.Marshal(msgBag)
if err != nil {
return nil, err
}
return b, nil
}
/*
UnpackJSON unpack json string.
*/
func UnpackJSON(msg []byte) (msgtype int, data []byte, err error) {
msgBag := &Msg{}
err = json.Unmarshal(msg, &msgBag)
if err != nil {
return 0, nil, err
}
return msgBag.Msgtype, msgBag.Data, nil
}
/*
IntToBytes int to bytes
*/
func IntToBytes(n int) []byte {
temp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, temp)
return bytesBuffer.Bytes()
}
/*
BytesToInt bytes to int
*/
func BytesToInt(b []byte) int {
bytesBuffer := bytes.NewBuffer(b)
var temp int32
binary.Read(bytesBuffer, binary.BigEndian, &temp)
return int(temp)
}
/*
Read read msg with header 4 byte.
*/
func Read(conn net.Conn) ([]byte, int, error) {
//conn.SetReadDeadline(time.Now().Add(1e9))
headerBuf := make([]byte, 4)
headerLen, err := conn.Read(headerBuf)
if err != nil || headerLen != 4 {
fmt.Println("read header failed:", err.Error(), headerLen)
return nil, 0, err
}
bodyLen := BytesToInt(headerBuf)
//fmt.Println("read head success, body len:", bodyLen)
bodyBuf := make([]byte, bodyLen)
readedbodyLen, err := conn.Read(bodyBuf)
if err != nil || readedbodyLen != int(bodyLen) {
fmt.Println("read body failed:", err.Error(), readedbodyLen)
return nil, 0, err
}
//fmt.Println("read body success,", bodyBuf)
return bodyBuf, bodyLen, nil
}
/*
Write write msg with header 4 byte
*/
func Write(conn net.Conn, msg string) error {
msgLen := strings.Count(msg, "") - 1
//fmt.Println(IntToBytes(msgLen))
_, err := conn.Write(IntToBytes(msgLen))
if err != nil {
fmt.Println("Write header failed.", err.Error())
return err
}
//fmt.Println([]byte(msg))
_, err = conn.Write([]byte(msg))
if err != nil {
fmt.Println("Write failed:", err.Error())
return err
}
return nil
}
godoc -http=:8080
然后就可以在浏览器里面输入 127.0.0.1:8080 来查看文档