提交 b9f5da04 编写于 作者: _Fighter's avatar _Fighter

2022年1月12日

上级 f8bd6924
......@@ -34,8 +34,6 @@
<change afterPath="$PROJECT_DIR$/nonrepeating/c.out" afterDir="false" />
<change afterPath="$PROJECT_DIR$/nonrepeating/cpu.out" afterDir="false" />
<change afterPath="$PROJECT_DIR$/queue/queue_test.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/errhandling/filelistingserver/filelisting/filelist.go" beforeDir="false" afterPath="$PROJECT_DIR$/errhandling/filelistingserver/filelisting/filelist.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/errhandling/filelistingserver/web.go" beforeDir="false" afterPath="$PROJECT_DIR$/errhandling/filelistingserver/web.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/go.mod" beforeDir="false" afterPath="$PROJECT_DIR$/go.mod" afterDir="false" />
......@@ -254,6 +252,7 @@
<workItem from="1657814506188" duration="1509000" />
<workItem from="1657816118798" duration="314000" />
<workItem from="1658072272414" duration="533000" />
<workItem from="1659928006697" duration="288000" />
</task>
<task id="LOCAL-00001" summary="2021年12月5日">
<created>1638720681912</created>
......@@ -353,7 +352,14 @@
<option name="project" value="LOCAL" />
<updated>1642004021802</updated>
</task>
<option name="localTasksCounter" value="15" />
<task id="LOCAL-00015" summary="2022年1月12日">
<created>1659928168332</created>
<option name="number" value="00015" />
<option name="presentableId" value="LOCAL-00015" />
<option name="project" value="LOCAL" />
<updated>1659928168333</updated>
</task>
<option name="localTasksCounter" value="16" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
......
mode: set
learngo/basic/basic.go:23.26,28.2 3 0
learngo/basic/basic.go:30.29,34.2 3 0
learngo/basic/basic.go:36.30,39.2 2 0
learngo/basic/basic.go:41.24,48.2 2 0
learngo/basic/basic.go:49.14,52.2 2 0
learngo/basic/basic.go:55.17,58.2 2 0
learngo/basic/basic.go:59.33,63.2 3 1
learngo/basic/basic.go:66.15,77.2 4 0
learngo/basic/basic.go:80.14,104.2 5 0
learngo/basic/basic.go:106.13,116.2 9 0
package main
import (
"bufio"
"fmt"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"golang.org/x/text/transform"
"io"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://www.zhenai.com/zhenghun")
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Println(" Error: status code ", resp.StatusCode)
return
}
// 自动发现见面编码
e := determineEncoding(resp.Body)
// 把内容以GBK编码读取
utf8Reader := transform.NewReader(resp.Body, e.NewDecoder())
all, err := ioutil.ReadAll(utf8Reader)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", all)
}
func determineEncoding(r io.Reader) encoding.Encoding {
bytes, err := bufio.NewReader(r).Peek(1024)
if err != nil {
panic(err)
}
e, _, _ := charset.DetermineEncoding(
bytes,
"",
)
return e
}
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func errPanic(writer http.ResponseWriter, request *http.Request) error {
fmt.Println(" this is an panic testing .....")
panic(6789)
//return nil
}
func errUserErr(writer http.ResponseWriter, request *http.Request) error {
//panic(6789)
fmt.Println(" this is an testing .....")
return testingUserError("user error")
}
type testingUserError string
func (e testingUserError) Error() string {
return e.Message()
}
func (e testingUserError) Message() string {
return string(e)
}
var tests = []struct {
h appHandler
code int
message string
}{
// {errPanic,500,"Internal Server Error"},
{errUserErr, 400, "user error"},
}
func TestErrWrapper(t *testing.T) {
for _, tt := range tests {
f := errWrapper(tt.h)
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "http:/www.baidu.com", bytes.NewBufferString("this is custome str "))
f(response, request)
b, _ := ioutil.ReadAll(response.Body)
body := strings.Trim(string(b), "\n")
if response.Code != tt.code || body != tt.message {
t.Errorf(" expect (%d ,%s) ; got (%d ,%s)", tt.code, tt.message, response.Code, body)
}
}
}
package filelisting
import (
"fmt"
"io/ioutil"
"net/http"
"os"
......@@ -21,6 +22,7 @@ func (e userError) Message() string {
func FileList(writer http.ResponseWriter, request *http.Request) error {
fmt.Println(" this is FileList func ")
if strings.Index(request.URL.Path, prefix) != 0 {
//return errors.New(" path must start with "+prefix)
return userError(" path must start with " + prefix)
......
package main
import (
"fmt"
"learngo/errhandling/filelistingserver/filelisting"
"log"
"net/http"
_ "net/http/pprof"
"os"
)
......@@ -13,8 +14,15 @@ type appHandler func(writer http.ResponseWriter, request *http.Request) error
func errWrapper(handler appHandler) func(writer http.ResponseWriter, request *http.Request) {
fmt.Println(" this is errWrapper func ")
return func(writer http.ResponseWriter, request *http.Request) {
fmt.Println(" this is return func ")
// recover 仅在defer 调用中使用
// 获取 panice 的值
// 如果无法处理时,可以重新 panic
defer func() {
if r := recover(); r != nil {
log.Printf("panic : %v", r)
http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
......
package main
import (
"fmt"
)
func tryRecover() {
defer func() {
r := recover()
if err, ok := r.(error); ok {
fmt.Println(" Error occurrend : ", err)
} else {
panic(r)
}
}()
// panic( errors.New("this is an error !"))
b := 0
a := 199 / b
fmt.Println(a)
}
func main() {
tryRecover()
}
daf
ad
fa
df
af
w
ef
wef
wf
\ No newline at end of file
module learngo
go 1.15
require (
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
golang.org/x/text v0.3.7
golang.org/x/tools v0.1.9 // indirect
)
github.com/yuin/goldmark v1.4.1 h1:/vn0k+RBvwlxEmP5E7SZMqNxPhfMVFEJiykr15/0XKM=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8=
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
package main
import (
"fmt"
"time"
)
// 协程 coroutine
// 轻量级"线程"
// 非抢占式多任务处理,邮协程主动交出控制权
//编译器/解释器/虚拟机层面的多任务
//多个协程可能在一个或多个线程上运行,它是有调度器决定的
// 切换控制权点:I/O ,select ,channel 等待锁,调用函数 runtime.Gosched()
func main() {
//var a [10]int
for i := 0; i < 1000; i++ {
go func(i int) {
for {
fmt.Printf("Hello form gorountine %d\n ", i) // 这个是一个io ,io 会进行切换 交出控制权
//a[i]++
//runtime.Gosched()// 手动交出控制权
}
}(i)
}
time.Sleep(time.Minute)
}
package main
import (
"fmt"
"net/http"
"net/http/httputil"
)
func main() {
request, err := http.NewRequest(http.MethodGet, "http://www.imooc.com", nil)
request.Header.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
clent := http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error {
fmt.Println("Redirect :", req)
return nil
}}
resp, err := clent.Do(request)
//resp ,err := http.DefaultClient.Do(request)
//resp ,err := http.Get("http://www.imooc.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
s, err := httputil.DumpResponse(resp, true)
if err != nil {
panic(err)
}
fmt.Printf(" %s\n", s)
}
package main
import (
"fmt"
"os"
)
func readMaze(filename string) [][]int {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
var row, col, z int
fmt.Fscanf(file, "%d %d %d", &row, &col, &z)
fmt.Printf("%d , %d, %d ", row, col, z)
fmt.Println()
// [][]int ,第一个方括号是一个slice ,第二个方括号是slice 里的元素
maze := make([][]int, row)
for i := range maze {
//每一行 多少列
maze[i] = make([]int, col)
for j := range maze[i] {
fmt.Fscanf(file, "%d", &maze[i][j])
}
}
return maze
}
// 当前点位
type point struct {
x, y int
}
var dirs = [4]point{
{-1, 0}, {0, -1}, {1, 0}, {0, 1},
}
//计算下一个点
func (p point) add(r point) point {
return point{p.x + r.x, p.y + r.y}
}
// 检查当前点是否越界
func (p point) at(grid [][]int) (int, bool) {
if p.x < 0 || p.x >= len(grid) {
return 0, false
}
if p.y < 0 || p.y >= len(grid[p.x]) {
return 0, false
}
return grid[p.x][p.y], true
}
func walk(maze [][]int, start, end point) [][]int {
steps := make([][]int, len(maze))
for i := range steps {
steps[i] = make([]int, len(maze[i]))
}
//起点加入队列
Q := []point{start}
for len(Q) > 0 {
cur := Q[0]
Q = Q[1:]
if cur == end {
break
}
for _, dir := range dirs {
next := cur.add(dir)
// 验证当前点位在迷宫中是否可以继续走
val, ok := next.at(maze)
if !ok || val == 1 {
continue
}
//验证当前点是否已经走过
val, ok = next.at(steps)
if !ok || val != 0 {
continue
}
//当前点与原点一致时
if next == start {
continue
}
curSteps, _ := cur.at(steps)
steps[next.x][next.y] = curSteps + 1
Q = append(Q, next)
}
}
return steps
}
func main() {
maze := readMaze("maze/maze.in")
/*for _,row := range maze {
for _, val := range row {
fmt.Printf(" %3d", val)
}
fmt.Println()
}*/
steps := walk(maze, point{0, 0}, point{len(maze) - 1, len(maze[0]) - 1})
for _, row := range steps {
for _, val := range row {
fmt.Printf("%3d", val)
}
fmt.Println()
}
}
6 8 0
0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0
0 1 0 1 0 0 1 0
1 1 1 0 0 1 0 0
0 1 0 0 1 1 0 1
0 1 0 0 0 0 0 0
mode: set
learngo/nonrepeating/nonrepeating.go:5.47,10.31 4 1
learngo/nonrepeating/nonrepeating.go:20.2,20.34 1 1
learngo/nonrepeating/nonrepeating.go:23.2,25.18 2 1
learngo/nonrepeating/nonrepeating.go:10.31,11.59 1 1
learngo/nonrepeating/nonrepeating.go:14.3,14.28 1 1
learngo/nonrepeating/nonrepeating.go:17.3,17.24 1 1
learngo/nonrepeating/nonrepeating.go:11.59,13.4 1 1
learngo/nonrepeating/nonrepeating.go:14.28,16.4 1 1
learngo/nonrepeating/nonrepeating.go:20.34,22.3 1 1
learngo/nonrepeating/nonrepeating.go:28.13,31.2 2 0
文件已添加
package main
package queue
import (
"fmt"
......
......@@ -3,14 +3,19 @@ package queue
// 定义别名
type Queue []interface{}
// push
func (q *Queue) Push(v interface{}) {
*q = append(*q, v)
}
// pop
func (q *Queue) Pop() interface{} {
head := (*q)[0]
*q = (*q)[1:]
return head
}
// is Empty
func (q *Queue) IsEmpty() bool {
return len(*q) == 0
}
package queue
import "fmt"
func ExampleQueue_Pop() {
q := Queue{1}
q.Push(2)
q.Push(3)
q.Push(3)
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
// Output:
//1
//2
//false
//3
//false
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册