南宁做网站设计方案,网站开发摊销多少年,上海网站建设建站,wordpress用外部图片本博文包含了go的math#xff0c;net/http#xff0c;fmt,io,csv#xff0c;time.Time,strconv,strings,sync.Pool的学习,笔记多是其实战如何用#xff0c;而非简单的函数式的讲解#xff0c;可谓是收藏佳作#xff0c;不时翻翻。 文章目录 1、math2、net/http3、fmt4、…本博文包含了go的mathnet/httpfmt,io,csvtime.Time,strconv,strings,sync.Pool的学习,笔记多是其实战如何用而非简单的函数式的讲解可谓是收藏佳作不时翻翻。 文章目录 1、math2、net/http3、fmt4、io打开文件写文件读文件文件拷贝 5.csv读取 6.json结构体转字符串结构体带tag版本json转struct组合json读取 7.time.Time按照格式输出当前文件输出时分秒年月日时间的格式化以及其他的时间使用 8.strconv9.strings10.sync.Pool11.ioutil 包12.os 包创建文件并写入读取文件内容创建目录检查文件或目录是否存在重命名文件删除文件或目录获取当前路径获取系统环境变量os.ReadFileos.WriteFile 13.flag 包命令行解析多个参数命令行解析位置参数 14.sort包对整数进行排序字符串切片排序自定义排序 15.reflect 包获取类型和反射值修改值判断类型和动态调用方法遍历结构体字段使用反射创建实例获取tag标签 16.context包创建和使用context.Backgroud()取消任务context.WithCancel()使用context.WithTimeout设置超时使用context.WithValue传递数据使用多个context配合工作 17.log包设置日期与时间戳日志记录到文件自定义输出错误日志日志记录到标准错误流 18.bufio包使用bufio.Reader进行读取使用bufio.Writer进行写入bufio.scanner逐行扫描输入 19.regexp包匹配包含字符串提取数字串替换数字查找匹配所有正则分组 参考文章 1、math
math包其他比较复杂常用的还是max,minabs几个因此写了这几个demo
func TestMath(t *testing.T) {//绝对值fmt.Println(math.Abs(-2.3))fmt.Println(math.Sqrt(8))fmt.Println(math.Round(5.2))fmt.Println(math.Floor(5.6))minInt : math.Min(2.3, 3.2)maxInt : math.Max(2.3, 3.2)fmt.Println(minInt, maxInt)}
2、net/http
func TestHttp(t *testing.T) {http.HandleFunc(/, helloHandler)fmt.Println(Starting server...)fmt.Println(http://127.0.0.1:8080)if err : http.ListenAndServe(:8080, nil); err ! nil {fmt.Println(Error starting server:, err)}
}// 简单的get请求
func handleRequest(w http.ResponseWriter, r *http.Request) {switch r.Method {case GET:fmt.Fprintf(w, This is a GET request)case POST:fmt.Fprintf(w, This is a POST request)default:http.Error(w, Method not allowed, http.StatusMethodNotAllowed)}
}// 复杂路由
func TestHttp2(t *testing.T) {http.HandleFunc(/, handleRequest)fmt.Println(Starting server...)fmt.Println(http://127.0.0.1:8081)if err : http.ListenAndServe(:8081, nil); err ! nil {fmt.Println(Error starting server:, err)}
}func userHandler(w http.ResponseWriter, r *http.Request) {vars : mux.Vars(r)userID : vars[id]fmt.Fprintf(w, Hello %s, userID)
}func TestHttp3(t *testing.T) {r : mux.NewRouter()r.HandleFunc(/users/{id}, userHandler).Methods(GET)fmt.Println(Starting server...:8080)fmt.Println(http://127.0.0.1:8082)if err : http.ListenAndServe(:8082, r); err ! nil {fmt.Println(Error starting server:, err)}
}func logginMiddleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {start : time.Now()next.ServeHTTP(w, r)duration : time.Since(start)log.Printf(%s %s %s %v, r.Method, r.URL.Path, r.RemoteAddr, duration)})
}
func helloHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, Hello World)
}func TestHttp4(t *testing.T) {router : http.NewServeMux()router.Handle(/,logginMiddleware(http.HandlerFunc(helloHandler)),)fmt.Println(Starting server on :8083)fmt.Println(http://127.0.0.1:8083)if err : http.ListenAndServe(:8083, router); err ! nil {fmt.Println(Error starting server:, err)}
}func TestHttp5(t *testing.T) {fs : http.FileServer(http.Dir(static))http.Handle(/static/, http.StripPrefix(/static/, fs))fmt.Println(Starting server on :8080)if err : http.ListenAndServe(:8080, nil); err ! nil {fmt.Println(Error starting server:, err)}
}func errorHandler(w http.ResponseWriter, r *http.Request, status int, message string) {w.WriteHeader(status)fmt.Fprintf(w, Error %d: %s, status, message)
}func handleRequest1(w http.ResponseWriter, r *http.Request) {if r.URL.Path /error {errorHandler(w, r, http.StatusInternalServerError, Internal Server Error)return}fmt.Fprintf(w, Hello World)
}func TestHttp6(t *testing.T) {http.HandleFunc(/, handleRequest1)fmt.Println(Starting server...)fmt.Println(http://127.0.0.1:8084)if err : http.ListenAndServe(:8084, nil); err ! nil {fmt.Println(Error starting server:, err)}
}func fetchURL(url string) (string, error) {resp, err : http.Get(url)if err ! nil {return , err}defer resp.Body.Close()body, err : ioutil.ReadAll(resp.Body)if err ! nil {return , err}return string(body), nil
}func TestHttp7(t *testing.T) {url : http://www.baidu.comcontent, err : fetchURL(url)if err ! nil {fmt.Println(err)return}fmt.Println(content)
}func postJSON(url string, data []byte) (string, error) {req, err : http.NewRequest(POST, url, bytes.NewBuffer(data))if err ! nil {return , err}req.Header.Set(Content-Type, application/json)client : http.Client{}resp, err : client.Do(req)if err ! nil {return , err}defer resp.Body.Close()body, err : ioutil.ReadAll(resp.Body)if err ! nil {return , err}return string(body), nil}func TestHttp8(t *testing.T) {url : http://jsonplaceholder.typicode.com/postsjsonData : []byte({title: foo, body:bar,userId:1})content, err : postJSON(url, jsonData)if err ! nil {fmt.Println(Error:, err)return}fmt.Println(content)
}
3、fmt
func TestFmt(t *testing.T) {fmt.Println(hello world)fmt.Print(hello world\n)fmt.Printf(hello\n)str : fmt.Sprintf(%s, hello world)fmt.Printf(str)
}
4、io
打开文件
func main() {file, err : os.Open(./a.txt)if err ! nil {fmt.Println(open file failed!,err:, err)return}file.Close()
}
写文件 file, err : os.Create(b.txt)if err ! nil {fmt.Println(err)return}defer file.Close()for i : 0; i 10; i {fmt.Fprintf(file, %d, i)file.WriteString(hello\n)file.Write([]byte(cd\n))}读文件 file, err : os.Open(./a.txt)if err ! nil {fmt.Println(open file err :, err)return}defer file.Close()var buf [128]bytevar content []bytefor {n, err : file.Read(buf[:])if err io.EOF {break}if err ! nil {fmt.Println(read file err :, err)return}content append(content, buf[:n]...)}fmt.Println(string(content))文件拷贝
srcFile, err : os.Open(./a.txt)if err ! nil {fmt.Println(err)return}dstFile, err : os.Create(./a2.txt)if err ! nil {fmt.Println(err)return}buf : make([]byte, 1024)for {n, err : srcFile.Read(buf)if err io.EOF {fmt.Println(读取完毕)break}if err ! nil {fmt.Println(err)break}dstFile.Write(buf[:n])}dstFile2, err : os.Create(./a4.txt)if err ! nil {fmt.Println(err)return}_, err io.Copy(dstFile2, srcFile)if err ! nil {fmt.Println(err)return}fmt.Println(File copied successfully)defer dstFile2.Close()
func re() {file, err : os.Open(./test.txt)if err ! nil {return}defer file.Close()reader : bufio.NewReader(file)for {line, _, err : reader.ReadLine()if err io.EOF {break}if err ! nil {return}fmt.Println(string(line))}
}
func wr() {file, err : os.OpenFile(test.txt, os.O_CREATE|os.O_WRONLY, 0666)if err ! nil {return}defer file.Close()writer : bufio.NewWriter(file)for i : 0; i 10; i {writer.WriteString(hello \n)}writer.Flush()
}func main() {wr()
}
5.csv
读取
type Person struct {Name string csv:nameAge int csv:age
}func read() {file, err : os.OpenFile(./csv.csv, os.O_RDWR|os.O_CREATE, 0666)if err ! nil {fmt.Println(打开文件失败, err)return}var person []*Personif err : gocsv.UnmarshalFile(file, person); err ! nil {fmt.Println(err)return}for _, v : range person {fmt.Printf(name: %s, age: %d\n, v.Name, v.Age)}defer file.Close()
}
func main() {read()
}
写入 type Person struct {Name string csv:nameAge int csv:age
}func write() {file, err : os.OpenFile(./csv.csv, os.O_RDWR|os.O_CREATE, 0666)if err ! nil {fmt.Println(打开文件失败, err)return}defer file.Close()people : []*Person{{Name: Alice, Age: 21},{Name: Bob, Age: 22},}if err : gocsv.Marshal(people, file); err ! nil {fmt.Println(写入文件失败, err)return}fmt.Println(写入成功)
}
func main() {write()
}
6.json
结构体转字符串
func struct_to_jsonstring() {user : UserInfo{Id: 1, Age: 18}b, err : json.Marshal(user)if err ! nil {fmt.Println(err)return}fmt.Println(string(b))
}func main() {struct_to_jsonstring()
}结构体带tag版本
type UserInfo struct {Id int json:idAge int json:age
}func struct_to_jsonstring() {user : UserInfo{Id: 1, Age: 18}b, err : json.Marshal(user)if err ! nil {fmt.Println(err)return}fmt.Println(string(b))
}func main() {struct_to_jsonstring()
}
json转struct
结构体还是上面的结构体代码取相反
func jsonstring_to_struct() {s : {Id:110,Age:18}var user UserInfoerr : json.Unmarshal([]byte(s), user)if err ! nil {fmt.Println(err)return}fmt.Println(user)fmt.Println(user.Id, user.Age)
}
func main() {jsonstring_to_struct()
}
组合json读取
相关的json文件
{title: 信号准入检查结果,time: 202230712123456789,author:{name:張三,age:18},body:[{group_item: 定位类,detail_list: [{check_item: 信号中的所有项,check_list: [{priority: P0, type: 完整性检查, check_desc: 具体描述1。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary1.txt},{priority: P0, type: 连续性检查, check_desc: 具体描述2。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary2.txt}]},{check_item: 经纬度,check_list: [{priority: P0, type: 异常检测跳变, check_desc: 具体描述3。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary3.txt},{priority: P0, type: 异常检测静止, check_desc: 具体描述4。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary4.txt}]}]},{group_item: 感知类,detail_list:[{check_item: 此类中所有必须项,check_list: [{priority: P0, type: 完整性检查, check_desc: 具体描述5。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary5.txt},{priority: P0, type: 连续性检查, check_desc: 具体描述6。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary8.txt}]},{check_item: 障碍物坐标信号『position』,check_list: [{priority: P0, type: 跳变异常, check_desc: 具体描述7。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary7.txt},{priority: P0, type: 超出路面异常, check_desc: 具体描述8。, result: 通过, conclusion_detail:ok, detail_reason: /tmp/sianal/summary8.txt}]}]}]
}package mainimport (encoding/jsonfmtio/ioutil
)type UserInfo struct {Id int json:idAge int json:age
}func struct_to_jsonstring() {user : UserInfo{Id: 1, Age: 18}b, err : json.Marshal(user)if err ! nil {fmt.Println(err)return}fmt.Println(string(b))
}func jsonstring_to_struct() {s : {Id:110,Age:18}var user UserInfoerr : json.Unmarshal([]byte(s), user)if err ! nil {fmt.Println(err)return}fmt.Println(user)fmt.Println(user.Id, user.Age)
}type CheckResultInfo struct {Title string json:titleTime string json:timeAuthor AuthorInfo json:authorBody []BodyInfo json:body
}type AuthorInfo struct {Name string json:nameAge int json:age
}type BodyInfo struct {GroupItem string json:group_itemDetailList []DetailInfo json:detail_list
}type DetailInfo struct {CheckItem string json:check_itemCheckList []CheckInfo json:check_list
}type CheckInfo struct {Priority string json:priorityType string json:typeCheckDesc string json:check_descResult string json:resultConclusionDetail string json:conclusion_detailDetailReason string json:detail_reason
}func common_deal_nestjson() {path : ./test.jsonf, _ : ioutil.ReadFile(path)var result CheckResultInfoerr : json.Unmarshal(f, result)if err ! nil {fmt.Println(err)return}for _, iv : range result.Body {fmt.Println(iv.GroupItem)for _, nv : range iv.DetailList {fmt.Println(nv.CheckItem)for _, cv : range nv.CheckList {fmt.Println(cv.Priority, cv.Type, cv.Result, cv.ConclusionDetail, cv.DetailReason)}}}}func main() {common_deal_nestjson()
}
7.time.Time
按照格式输出当前文件
func main() {currentTime : time.Now()fmt.Println(currentTime.Format(2006-01-02 15:04:05))
}
输出时分秒年月日
func main() {fmt.Println(年, time.Now().Year())fmt.Println(月, time.Now().Month())fmt.Println(日, time.Now().Day())fmt.Println(小时, time.Now().Hour())fmt.Println(分钟, time.Now().Minute())fmt.Println(秒, time.Now().Second())fmt.Println(纳秒, time.Now().Nanosecond())fmt.Println(星期几, time.Now().Weekday())
}
时间的格式化以及其他的时间使用
fmt.Println(Unix 时间戳(秒):, time.Now().Unix())fmt.Println(Unix时间戳(纳秒), time.Now().UnixNano())fmt.Println(年-月-日, time.Now().Format(2006-01-02))fmt.Println(时:分:秒, time.Now().Format(15:04:05))fmt.Println(时:分:秒 PM, time.Now().Format(15:04:05 PM))//时间解析timeStr : 2025-03-08 15:04:05parsedTime, err : time.Parse(2006-01-02 15:04:05, timeStr)if err ! nil {fmt.Println(解析时间出错, err)} else {fmt.Println(解析后的时间, parsedTime)}//模拟耗时time.Sleep(1 * time.Second)//模拟用时startTime : time.Now()time.Sleep(1 * time.Second)elapsedTime : time.Since(startTime)fmt.Println(操作耗时:, elapsedTime)//时间加减nextWeek : time.Now().Add(7 * 24 * time.Hour)fmt.Println(一周后的时间, nextWeek)yesterday : time.Now().Add(-24 * time.Hour)fmt.Println(一周前的时间, yesterday)//时间差计算startTime time.Date(2025, 3, 12, 12, 12, 0, 0, time.Local)duration : time.Now().Sub(startTime)fmt.Println(时间差:, duration)//延时执行fmt.Println(延时3秒执行)time.Sleep(3 * time.Second)fmt.Println(延时结束)//延时触发select {case -time.After(1 * time.Second):fmt.Println(1秒后执行)}//周期性触发ticker : time.NewTicker(1 * time.Second)go func() {for t : range ticker.C {fmt.Println(每秒触发1次当前时间:, t)}}()time.Sleep(1 * time.Second)ticker.Stop()fmt.Println(Ticker已停止)//一次性定时器timer : time.NewTimer(3 * time.Second)fmt.Println(等待3秒)-timer.Cfmt.Println(Timer 触发)//换时区loc, _ : time.LoadLocation(Asia/Tokyo)nyTime : time.Now().In(loc)fmt.Println(泰国时间:, nyTime)//随机时间生成randomDuration : time.Duration(rand.Intn(1000)) * time.MillisecondrandomTime : time.Now().Add(randomDuration)fmt.Println(随机时间, randomTime)8.strconv
一些操作 //strconvvar i int 10fmt.Println(返回字符串, strconv.Itoa(i))j : 12.233fmt.Println(将浮点数转换, strconv.FormatFloat(j, f, 2, 64))strValue : 245atoi, err : strconv.Atoi(strValue)fmt.Println(字符串转int, atoi, err)strFloat : 12.333float, err : strconv.ParseFloat(strFloat, 64)fmt.Println(字符串转float, float, err)9.strings
func main() {var str string this is an examplefmt.Println(strings.HasPrefix(str, th))fmt.Println(字符串包含:, strings.Contains(str, is))fmt.Println(子串索引, strings.Index(str, th))var strChines []rune(中国)fmt.Println(子串包含, strings.ContainsRune(string(strChines), 中))fmt.Println(子串包含, strings.IndexRune(string(strChines), 中))fmt.Println(子串从后往前找, strings.LastIndex(str, example))fmt.Println(子串替换, strings.Replace(str, is, as, 1))fmt.Println(统计:, strings.Count(str, s))fmt.Println(字符串重复, strings.Repeat(str, 2))fmt.Println(字符串转大写, strings.ToLower(str))fmt.Println(字符串转小写, strings.ToUpper(str))fmt.Println(修剪字符串, strings.TrimSpace(str))fmt.Println(分割字符串, strings.Split(str, ))strSlice : []string{This, is, a, apple}fmt.Println(拼接字符串, strings.Join(strSlice, ))}10.sync.Pool
func main() {var bufferPool sync.Pool{New: func() interface{} {return make([]byte, 1024)},}buffer : bufferPool.Get().([]byte)fmt.Println(缓冲区内容, len(buffer))copy(buffer, hello,sync.Pool)fmt.Println(缓冲区内容, string(buffer[:18]))//放入bufferPool.Put(buffer)//获取anotherBuffer : bufferPool.Get().([]byte)fmt.Println(len(anotherBuffer))
}
11.ioutil 包
Go 1.16 开始ioutil 中的函数被移到了其他包中。例如
ioutil.ReadFile → os.ReadFileioutil.WriteFile → os.WriteFileioutil.ReadAll → io.ReadAllioutil.NopCloser → io.NopCloser
因此ioutil包不进行学习其操作了将放在
12.os 包
创建文件并写入
file, err : os.Create(example.txt)if err ! nil {fmt.Println(Error Creating file:, err)return}defer file.Close()_, err file.WriteString(Hello,Test!)if err ! nil {fmt.Println(Error Writing to file., err)return}fmt.Println(文件写入完毕)读取文件内容
package mainimport (fmtos
)func main() {file, err : os.Open(example.txt)if err ! nil {fmt.Println(Error opening file:, err)return}defer file.Close()stat, err : file.Stat()if err ! nil {fmt.Println(Error getting file stats:, err)return}data : make([]byte, stat.Size())_, err file.Read(data)if err ! nil {fmt.Println(Error reading file:, err)return}fmt.Println(file content:, string(data))}
创建目录
func main() {err : os.Mkdir(tmpDir, 0755)if err ! nil {fmt.Println(Error creating directory:, err)return}fmt.Println(Directory created successfully)
}检查文件或目录是否存在 func main() {_, err : os.Stat(example.txt)if os.IsNotExist(err) {fmt.Println(file does not exist)} else if err ! nil {fmt.Println(Error checking file:, err)} else {fmt.Println(File exists.)}_, err os.Stat(tmpDir)if os.IsNotExist(err) {fmt.Println(dir does not exist)} else if err ! nil {fmt.Println(Error checking file:, err)} else {fmt.Println(Directory exists.)}}
重命名文件
func main() {err : os.Rename(example.txt, test.txt)if err ! nil { fmt.Println(Error renaming file, err)return}fmt.Println(File named successfully)
}删除文件或目录
func main() {err : os.Remove(test.txt)//目录名就可以删除目录了if err ! nil {fmt.Println(Error remove file, err)return}fmt.Println(File remove successfully)
}
获取当前路径
func main() {dir, err : os.Getwd()if err ! nil {fmt.Println(Error getting current directory, err)return}fmt.Println(Current directory, dir)
}
获取系统环境变量
func main() {value : os.Getenv(JAVA_HOME)if value {fmt.Println($JAVA_HOME not set)} else {fmt.Println(JAVA_HOME environment variable:, value)}
}
os.ReadFile
package mainimport (fmtos
)func main() {data, err : os.ReadFile(hello.txt)if err ! nil {fmt.Println(error:, err)return}fmt.Println(string(data))}os.WriteFile
将内容写到hello.txt
package mainimport (fmtos
)func main() {content : []byte(hello,this is the content,written using os.WriteFile)err : os.WriteFile(hello.txt, content, 0644)if err ! nil {fmt.Println(Error writting to file:, err)return}fmt.Println(Content written to file successfully)
}
13.flag 包
多用于解析命令行所使用
命令行解析多个参数
package mainimport (flagfmt
)func main() {name : flag.String(name, gopher, your name)age : flag.Int(age, 18, your age)isStudent : flag.Bool(student, false, Are you a student?)flag.Parse()fmt.Printf(Name: %s, Age: %d,Student:%t\n, *name, *age, *isStudent)
}
命令行解析位置参数
package mainimport (flagfmt
)func main() {name : flag.String(name, gopher, your name)flag.Parse()fmt.Printf(Hello %s!\n, *name)args : flag.Args()if len(args) 0 {fmt.Println(Additional arguments:)for _, arg : range args {fmt.Println(arg)}} else {fmt.Println(No additional arguments.)}
}14.sort包
sort包主要用来排序使用
对整数进行排序
package mainimport (fmtsort
)func main() {numbers : []int{5, 3, 8, 1, 7}//使用sort.Ints排序sort.Ints(numbers)fmt.Println(numbers)
}字符串切片排序
package mainimport (fmtsort
)func main() {strings : []string{banana, apple, cherry, mango}sort.Strings(strings)fmt.Println(Sorted strings, strings)
}
自定义排序
package mainimport (fmtsort
)type Person struct {Name stringAge int
}type ByAge []Personfunc (a ByAge) Len() int { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age a[j].Age }
func (a ByAge) Swap(i, j int) { a[i], a[j] a[j], a[i] }func main() {people : []Person{{John, 30},{Alice, 25},{Bob, 25},}sort.Sort(ByAge(people))fmt.Println(people)
}
15.reflect 包
获取类型和反射值
package mainimport (fmtreflect
)func main() {var x int 42t : reflect.TypeOf(x)v : reflect.ValueOf(x)//打印类型和反射值fmt.Println(Type:, t)fmt.Println(Value:, v)
}
修改值
type Person struct {Name stringAge int
}func main() {p : Person{Name: Bob, Age: 18}v : reflect.ValueOf(p).Elem()v.FieldByName(Name).SetString(Alice)v.FieldByName(Age).SetInt(14)fmt.Println(Undated Person:, p)
}判断类型和动态调用方法
type Greeter struct {Message string
}func (g Greeter) Greet(name string) {fmt.Println(g.Message)
}func main() {g : Greeter{Hello World}v : reflect.ValueOf(g)method : v.MethodByName(Greet)if method.IsValid() {args : []reflect.Value{reflect.ValueOf(Hello World)}method.Call(args)} else {fmt.Println(Method not found)}
}遍历结构体字段
type Person struct {Name stringAge int
}func main() {p : Person{Name: John, Age: 30}v : reflect.ValueOf(p)for i : 0; i v.NumField(); i {field : v.Field(i)fieldName : v.Type().Field(i).Namefmt.Println(fieldName, field, field.Interface())}
}使用反射创建实例
package mainimport (fmtreflect
)func main() {t : reflect.TypeOf(0)v : reflect.New(t).Elem()fmt.Println(New Value:, v)fmt.Println(Type of new Value, v.Type())
}
获取tag标签
package mainimport (fmtreflect
)type Person struct {Name string json:nameAge int json:age
}func main() {t : reflect.TypeOf(Person{})for i : 0; i t.NumField(); i {field : t.Field(i)tag : field.Tag.Get(json)fmt.Printf(%s: %s\n, tag, field.Name)}
}16.context包
创建和使用context.Backgroud()
package mainimport (contextfmttime
)func main() {ctx : context.Background()doSomething(ctx)
}func doSomething(ctx context.Context) {select {case -time.After(1 * time.Second):fmt.Println(Operation Completed)case -ctx.Done():fmt.Println(Context canceled, ctx.Err())}
}
取消任务context.WithCancel()
package mainimport (contextfmttime
)func main() {ctx, cancel : context.WithCancel(context.Background())go doWork(ctx)time.Sleep(5 * time.Second)cancel()time.Sleep(1 * time.Second)
}func doWork(ctx context.Context) {for {select {case -time.After(1 * time.Second):fmt.Println(working...)case -ctx.Done():fmt.Println(work canceled:, ctx.Err())return}}
}
使用context.WithTimeout设置超时
package mainimport (contextfmttime
)func main() {ctx, cancel : context.WithTimeout(context.Background(), 2*time.Second)defer cancel()err : doTask(ctx)if err ! nil {fmt.Println(Error:, err)}
}func doTask(ctx context.Context) (err error) {select {case -time.After(3 * time.Second):fmt.Println(Task completed)return nilcase -ctx.Done():return fmt.Errorf(timed out:%v, ctx.Err())}
}
使用context.WithValue传递数据
package mainimport (contextfmt
)type key stringconst requestIDKey key requestIDfunc main() {ctx : context.WithValue(context.Background(), requestIDKey, 12345)processRequest(ctx)
}func processRequest(ctx context.Context) {requestID : ctx.Value(requestIDKey).(string)fmt.Println(Processing request with ID:, requestID)
}
使用多个context配合工作
package mainimport (contextfmttime
)func main() {ctx, cancel : context.WithCancel(context.Background())ctx, timeoutCancel : context.WithTimeout(ctx, 3*time.Second)defer timeoutCancel()go doWork(ctx)time.Sleep(time.Second * 2)cancel()time.Sleep(time.Second * 1)
}func doWork(ctx context.Context) {select {case -time.After(time.Second * 5):fmt.Println(time out)case -ctx.Done():fmt.Println(Task cancelled or time out:, ctx.Err())}
}
17.log包
设置日期与时间戳
func main() {log.SetPrefix(INFO: )log.SetFlags(log.Ldate | log.Ltime)log.Println(Hello World)
}
日志记录到文件
package mainimport (logos
)func main() {file, err : os.OpenFile(example.log, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)if err ! nil {log.Fatal(err)}defer file.Close()log.SetOutput(file)log.Println(This log is written to a file.)
}
自定义输出错误日志
package mainimport (logos
)func main() {customLogger : log.New(os.Stderr, CUSTOM LOG, log.Ldate|log.Ltime|log.Lshortfile)file, err : os.Open(abc.txt)if err ! nil {customLogger.Fatal(err)}defer file.Close()customLogger.Println(File opened successfully)
}
日志记录到标准错误流
log.SetOutput(os.Stderr)18.bufio包
使用bufio.Reader进行读取
使用ReadLine也可以
package mainimport (bufiofmtos
)func main() {file, err : os.Open(hello.txt)if err ! nil {fmt.Println(Error opening file:, err)return}defer file.Close()reader : bufio.NewReader(file)for {line, err : reader.ReadString(\n)//也可使用ReadLineif err ! nil {break}fmt.Print(line)}
}
使用bufio.Writer进行写入
package mainimport (bufiofmtos
)func main() {file, err : os.Create(hello.txt)if err ! nil {fmt.Println(Error creating file:, err)return}defer file.Close()//使用bufio.NewWriter创建一个带缓冲的写入器writer : bufio.NewWriter(file)writer.WriteString(Hello,this is a buffered write.\n)writer.WriteString(This is the second line.\n)writer.Flush()}
bufio.scanner逐行扫描输入
package mainimport (bufiofmtos
)func main() {scanner : bufio.NewScanner(os.Stdin)//提示用户输入fmt.Println(Please enter text (CtrlD):)for scanner.Scan() {line : scanner.Text()fmt.Println(You entered:, line)}if err : scanner.Err(); err ! nil {fmt.Println(Error reading input:, err)}
}19.regexp包
匹配包含字符串
func main() {re : regexp.MustCompile(\d)str : hello 123 worldif re.MatchString(str) {fmt.Println(compatible success)} else {fmt.Println(compatible success)}}提取数字串
package mainimport (fmtregexp
)func main() {re : regexp.MustCompile(\d{3}-\d{3}-\d{3})str : 我的电话号码是 110-120-119watch : re.FindString(str)fmt.Println(匹配到的电话号码:, watch)}
替换数字
func main() {re : regexp.MustCompile(\d)str : 今年是2025年,明年是2026年result : re.ReplaceAllString(str, 数字)fmt.Println(result)
}查找匹配所有
func main() {re : regexp.MustCompile(\w)str : go is the best languagewords : re.FindAllString(str, -1)fmt.Println(查找到所有单词, words)
}
正则分组
package mainimport (fmtregexp
)func main() {re : regexp.MustCompile((\d{4})-(\d{2})-(\d{2}))str : 今天是 2025-03-10match : re.FindStringSubmatch(str)if match ! nil {fmt.Println(完整匹配:, match[0])fmt.Println(年份:, match[1])fmt.Println(月份:, match[2])fmt.Println(日期:, match[3])}
}
参考文章
文章1 文章2:io 文章三json 文章4time