每天坚持20分钟go常用的包

2022-07-03 23:59:07 浏览数 (2)

go常用的内置库

  • 字符串操作
  • bytes
  • json
  • io/bufio
  • fmt
  • strconv
  • time
  • regexp
  • log
  • reflect/unsafe
  • os/path/filepath
  • unicode
  • flag
  • net/url
  • net/http
  • sort
  • error
代码语言:go复制
package main

import (
	"bufio"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"
	"unicode"
	"unsafe"
)

var (
	numberOne int
	nameOne   string
)

//error
type MyError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func NewMyError(code int, msg string) *MyError {
	return &MyError{code, msg}
}

func (self MyError) Error() string {
	return fmt.Sprintf("code:%d, msg:%s", self.Code, self.Msg)
}

func main() {
	//字符串,各类操作
	//包含,替换,分隔
	str := "hello world"
	fmt.Println(strings.Contains(str, "hello"))
	str_slice1 := strings.Split(str, " ")
	fmt.Println(strings.Join(str_slice1, "#"))
	fmt.Println(strings.NewReplacer("h", "k", " ", "#", "d", "a").Replace(str))

	//bytes
	byte1 := []byte(str)
	fmt.Println(byte1)

	//json
	type Person struct {
		Name string `json:"n, omitempty"`
		Age  int    `json:"a, omitempty"`
	}
	p := &Person{Name: "tom", Age: 31}
	data, _ := json.Marshal(p)
	fmt.Printf("data:%sn", data)
	p2 := &Person{}
	err := json.Unmarshal(data, p2)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Printf("% v", p2)

	//buffer
	f, err := os.Open("gobase_ch1.go")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	rb := bufio.NewReader(f)
	for {
		line, err := rb.ReadString('n')
		if err != nil || io.EOF == err {
			break
		}
		fmt.Println(line)
	}

	//strconv
	fmt.Println(strconv.Atoi("12"))

	//time
	time1 := time.Now()
	fmt.Println(time1, time1.Second(), time1.UnixMilli())
	ticker1 := time.NewTicker(time.Second * 1)
	defer ticker1.Stop()
	done := make(chan bool)
	go func() {
		time.Sleep(3 * time.Second)
		done <- true
	}()

BreakTag:
	for {
		select {
		case <-done:
			fmt.Println("Done!")
			break BreakTag
		case t := <-ticker1.C:
			fmt.Println("current time: ", t)
		}
	}

	//error
	fmt.Println(NewMyError(124, "test"))

	//regexp
	reg, err := regexp.Compile("l")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("查找到字符串:", reg.FindString(str))

	//log
	log.Println("test")
	logger := log.New(os.Stdout, "java", log.Lshortfile)
	logger.Println("hello rust")

	//reflect unsafe
	var a int = 333
	type1 := reflect.TypeOf(a)
	value1 := reflect.ValueOf(a)
	fmt.Println(type1, value1)

	fmt.Println(unsafe.Sizeof(p))
	ptr := unsafe.Pointer(p)
	fmt.Println(ptr)
	fmt.Println(*((*string)(ptr)))

	secondField := unsafe.Pointer(uintptr(ptr)   unsafe.Offsetof(p.Age))
	fmt.Println(secondField)
	fmt.Println(*(*int)(secondField))

	//os path filepath
	fileMode, err := os.Stat("gobase.go")

	if os.IsExist(err) {
		fmt.Println(fileMode.Name(), fileMode.Size(), fileMode.Mode())
	} else {
		fmt.Println("not exist")
	}

	str2, err := ioutil.ReadFile("gobase_ch1.go")
	fmt.Println("len=", len(str2))

	//unicode
	fmt.Println(unicode.IsNumber(rune(123)))

	//flag
	flag.IntVar(&numberOne, "n", 10, "number")
	nameOne = *flag.String("name", "tom", "a person'name")
	flag.Parse()
	fmt.Printf("name=%s, number:%d", nameOne, numberOne)

	//net/url
	var urlStr string = "https://rustcc.cn/article?id=0732244c-9a1b-41ac-b22d-825b6674b671"
	vdata, _ := url.Parse(urlStr)
	fmt.Printf("%#vn", vdata)

	//sort
	list1 := []int{3, 5, 1, 4}
	sort.Ints(list1)
	fmt.Println(list1)

	//net/http
	//client
	resp1, err := http.Get(urlStr)
	if err != nil {
		fmt.Println(err)
	}
	defer resp1.Body.Close()
	content, _ := ioutil.ReadAll(resp1.Body)
	fmt.Println(len(string(content)))

	//server
	http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello"))
	})
	log.Fatal(http.ListenAndServe(":8181", nil))

}

0 人点赞