go 语言 基础知识点二 - Go语言中文社区

go 语言 基础知识点二


 

更多干货

 

 

Go协程

package main

import (
	"fmt"
	"time"
)

func test_Routine() {
	fmt.Println("This is one routine!!!")
}

func Add(x, y int) {
	z := x + y
	fmt.Println(z)
}

func main() {
	for i := 1; i < 10; i++ {
		go Add(i, i)
	}

	time.Sleep(2)
}

channel

package main

import (
	"fmt"
	"strconv"
)

func Add(x, y int, quit chan int) {
	z := x + y
	fmt.Println(z)

	quit <- 1
}

func Read(ch chan int) {
	value := <-ch

	fmt.Println("value:" + strconv.Itoa(value))
}

func Write(ch chan int) {
	//ch <- 10
}

func main() {
	//ch := make(chan int)
	//go Read(ch)
	//go Write(ch)

	//time.Sleep(10)

	//fmt.Println("end of code")

	chs := make([]chan int, 10)
	for i := 0; i < 10; i++ {
		chs[i] = make(chan int)
		go Add(i, i, chs[i])
	}

	for _, v := range chs {
		<-v
	}
}

缓冲channel

package main

import (
	"fmt"
	"time"
)

var ch chan int

func test_channel() {
	ch <- 1
	fmt.Println("ch 1")
	ch <- 1
	fmt.Println("ch 2")
	ch <- 1
	fmt.Println("come to end goroutine 1")
}

func main() {
	ch = make(chan int, 0) // 等价于 ch = make(chan int) 都是不带缓冲的channel
	ch = make(chan int, 2) // 是带缓冲的channel
	go test_channel()
	time.Sleep(2 * time.Second)
	fmt.Println("running end!")
	<-ch

	time.Sleep(time.Second)
}

Go语言select

package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan int)

	go func(ch chan int) {
		ch <- 1
	}(ch)

	time.Sleep(time.Second)

	select {
	case <-ch:
		fmt.Print("come to read ch!")
	default:
		fmt.Print("come to default!")
	}
}

 

 

package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan int)
	timeout := make(chan int, 1)

	go func() {
		time.Sleep(time.Second)
		timeout <- 1
	}()

	select {
	case <-ch:
		fmt.Print("come to read ch!")
	case <-timeout:
		fmt.Print("come to timeout!")
	}

	fmt.Print("end of code!")
}
package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan int)

	select {
	case <-ch:
		fmt.Print("come to read ch!")
	case <-time.After(time.Second):
		fmt.Print("come to timeout!")
	}

	fmt.Print("end of code!")
}
package main

import (
	"fmt"
	"runtime"
	"strconv"
	"time"
)

func main() {
	//协程1
	go func() {
		for i := 1; i < 100; i++ {
			if i == 10 {
				//主动出让cpu 使用的话 需要 导入 runtime包
				runtime.Gosched()
			}
			fmt.Println("routine 1:" + strconv.Itoa(i))
		}
	}()

	//协程2
	go func() {
		for i := 100; i < 200; i++ {
			fmt.Println("routine 2:" + strconv.Itoa(i))
		}
	}()

	time.Sleep(time.Second)
}
package main

import (
	"fmt"
	"strconv"
	"time"
)

var ch chan int

func main() {
	ch = make(chan int)
	//协程1
	go func() {
		for i := 1; i < 100; i++ {
			if i == 10 {
				//遇到了阻塞
				<-ch
			}
			fmt.Println("routine 1:" + strconv.Itoa(i))
		}
	}()

	//协程2
	go func() {
		for i := 100; i < 200; i++ {
			fmt.Println("routine 2:" + strconv.Itoa(i))
		}

		ch <- 1
	}()

	time.Sleep(time.Second)
}

 

协程 默认不会主动让出执行权,即一个协程执行完后才会让出cpu 让另外的协程执行。除非以下两种情况协程让出cpu

 

JSONMd5

package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Name string `json:"student_name"`
	Age  int
}

func main() {
	//对数组类型的json编码
	x := [5]int{1, 2, 3, 4, 5}
	s, err := json.Marshal(x)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(s))

	//对map类型进行json编码
	m := make(map[string]float64)
	m["zhangsan"] = 100.4
	s2, err2 := json.Marshal(m)
	if err2 != nil {
		panic(err2)
	}

	fmt.Println(string(s2))

	//对对象进行json编码
	student := Student{"zhangsan", 26}
	s3, err3 := json.Marshal(student)
	if err3 != nil {
		panic(err3)
	}

	fmt.Println(string(s3))

	//对s3进行json解码
	var s4 interface{}
	json.Unmarshal([]byte(s3), &s4)
	fmt.Printf("%v", s4)
}

 

package main

import (
	"crypto/md5"
	"fmt"
)

func main() {
	Md5Inst := md5.New()
	Md5Inst.Write([]byte("zhangsan"))
	Result := Md5Inst.Sum([]byte(""))
	fmt.Printf("%xnn", Result)
}

HTTP

package main

import (
	//"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello beifeng!"))
	})

	http.ListenAndServe("127.0.0.1:8080", nil)
}

该方法用于在指定的 TCP 网络地址 addr 进行监听,然后调用服务端处理程序来处理传入的连 接请求。该方法有两个参数:第一个参数 addr 即监听地址;第二个参数表示服务端处理程序, 通常为空,这意味着服务端调用 http.DefaultServeMux 进行处理,而服务端编写的业务逻 辑处理程序 http.Handle()http.HandleFunc() 默认注入 http.DefaultServeMux 中

 

路由

http.HandleFunc()方法接受两个参数

第一个参数是HTTP请求的 目标路径"/hello",该参数值可以是字符串,也可以是字符串形式的正则表达式

第二个参数指定具体的回调方法,比如helloHandler。

当我们的程序运行起来后,访问http://localhost:8080/hello  , 程序就会去调用helloHandler()方法中的业务逻辑程序

http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(“hello beifeng!”))
	})

get/post访问

resp, err:=http.Get(“.....”)

defer resp.Body.Close()

body,err:=ioutil.ReadAll(resp.Body)

fmt.Println(string(body))
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func main() {
	resp, err := http.Post("http://www.baidu.com", "application/x-www-form-urlencoded", strings.NewReader("id=1"))
	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

正则表达式

. 	匹配除换行符以外的任意字符
w 	匹配字母或数字或下划线或汉字
s 	匹配任意的空白符
d 	匹配数字
b 	匹配单词的开始或结束
^ 	匹配字符串的开始
$ 	匹配字符串的结束
* 	重复零次或更多次
+ 	重复一次或更多次
? 	重复零次或一次
{n} 	重复n次
{n,} 	重复n次或更多次
{n,m} 	重复n到m次
捕获 (exp) 	匹配exp,并捕获文本到自动命名的组里

(?<name>exp) 	匹配exp,并捕获文本到名称为name的组里,也可以写成(?'name'exp)

(?:exp) 		匹配exp,不捕获匹配的文本,也不给此分组分配组号

 

package main

import (
	"fmt"
	"regexp"
)

func main() {
	//reg := regexp.MustCompile("\w+") 正则表达式中的需要转义
	reg := regexp.MustCompile(`^z.*l$`)

	result := reg.FindAllString("zhangsanl", -1)
	fmt.Printf("%vn", result)

	reg1 := regexp.MustCompile(`^z(.*)l$`)

	result1 := reg1.FindAllString("zhangsand", -1)
	fmt.Printf("%vn", result1)

	reg2 := regexp.MustCompile(`^z(.{1})(.{1})(.*)l$`)

	result2 := reg2.FindAllStringSubmatch("zhangsanl", -1)
	fmt.Printf("%vn", result2)
}
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
)

func main() {
	url := "https://movie.douban.com/subject/24751763/"
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()

	sHtml, _ := ioutil.ReadAll(resp.Body)

	reg := regexp.MustCompile(`<spans*property="v:itemreviewed">(.*)</span>`)
	result := reg.FindAllStringSubmatch(string(sHtml), -1)

	fmt.Println(result[0][1])

	reg1 := regexp.MustCompile(`<strongs*class="lls*rating_num"s*property="v:average">(.*)</strong>`)
	result1 := reg1.FindAllStringSubmatch(string(sHtml), -1)

	fmt.Println(result1[0][1])
}

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_27384769/article/details/83791827
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-02 19:10:47
  • 阅读 ( 889 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢