天天看點

Go語言學習心路

前言

Go作為新生的語言,由于其速度快,以及一系列優點越來越流行。

下載下傳

  • golang.google.cn
  • gomirrors
  • https://golang.org 官網估計要翻牆

windows使用者點選這個即可:

Go語言學習心路

而linux使用者則:

yum install golang
           

配置鏡像

參考這篇文章: go module基本使用 親測可行。

簡要步驟如下:

set GO111MODULE=on
           

不過在下載下傳beego(go get github.com/beego/beego/[email protected])的時候,上面這個我覺得好像沒有下面這句管用

go env -w GO111MODULE=on
           

設定七星雲鏡像:

go env -w GOPROXY=https://goproxy.cn,direct
           
  • 阿裡雲鏡像: https://mirrors.aliyun.com/goproxy/
  • 中國golang鏡像: https://goproxy.io

初始化:

go mod init 【項目名字】
           

更新依賴檔案, 若找到需要下載下傳的依賴檔案則會自動download:

go mod tidy
           

下載下傳依賴檔案, 這個操作非必須。

go mod download
           

如果使用vscode進行開發的話,再下載下傳多一個插件即可:

Go語言學習心路

推薦教程

  • (中英字幕) Go語言基礎課程(Golang Tutorial) 第一集暫時沒有字幕好像,當練習聽力吧,第一集也沒有什麼重點内容。然後下面一些語句記錄很多來源于這裡。
  • Go 語言教程(菜鳥教程)
  • 使用Golang建構一個社交網絡課程 ( Building a Social Network with Golang )

一些語句記錄

來源于(中英字幕) Go語言基礎課程(Golang Tutorial) 的學習記錄。不過不會完全一緻,敲得時候比較随意hhh,想着隻要get到大意即可。

讀取鍵盤輸入

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print("When were you born?(type year): ")
	scanner.Scan()
	input, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	fmt.Printf("You are %d years old when 2020", 2020-input)
}
           

output:(鍵盤輸入2005)

When were you born?(type year): 2005
You are 15 years old when 2020
           

函數

多個傳回值:

package main

import (
	"fmt"
)

func add(x, y, z int) (int, int) {
	return x + y, y + z
}

func main() {
	ans, ans2 := add(6, 7, 8)
	fmt.Println(ans, ans2)
}
           

output:

13 15
           

一個其他語言不常見的寫法:

package main

import (
	"fmt"
)

func add(x, y, z int) (a, b int) {
	// 延遲到return在執行,可用于關閉檔案等操作
	defer fmt.Println("hello")
	a = x + y
	b = y + z
	fmt.Println("Before return")
	return
}

func main() {
	ans, ans2 := add(6, 7, 8)
	fmt.Println(ans, ans2)
}
           

output:

Before return
hello
13 15
           

進階函數

package main

import (
	"fmt"
)

func returnFunc(x string) func() {
	return func() {
		fmt.Println(x)
	}
}

func main() {
	returnFunc("hello")()
	returnFunc("goodbye")()
}
           
Go語言學習心路
package main

import (
	"fmt"
)

func test2(myFunc func(int) int) {
	fmt.Println(myFunc(7))
}

func main() {
	test := func(x int) int {
		return x * -1
	}
	test2(test)
}
           

output:

-7
           

“引用”

從輸出發現會改變傳入的數組的值:

package main

import "fmt"

func changeList(list []int) {
	list[0] = 250
}

func main() {
	a := []int{1, 2}
	fmt.Println(a)
	changeList(a)
	fmt.Println(a)
}
           

output:

[1 2]
[250 2]
           
package main

import "fmt"

func main() {
	var x map[string]int = map[string]int{"hello": 3}
	y := x
	y["y"] = 100
	x["7"] = 7
	fmt.Println(x, y)
}
           

output:

package main

import "fmt"

func main() {
	var x []int = []int{3, 4, 5}
	y := x
	x[0] = 250
	fmt.Println(x, y)
}
           

output:

指針

package main

import "fmt"

func main() {
	x := 7
	y := &x
	fmt.Println(x, y)
	*y = 8
	fmt.Println(x, y)
}
           

output:

7 0xc000014080
8 0xc000014080
           
package main

import "fmt"

func changeValue(str *string) {
	*str = "bye!"
}

func changeValue2(str string) {
	str = "goodbye!"
}

func main() {
	strValue, strValue2 := "hello", "hello"
	changeValue(&strValue)
	fmt.Println(strValue)
	changeValue2(strValue2)
	fmt.Println(strValue2)
}
           

output:

bye!
hello
           

結構體

package main

import "fmt"

type Point struct {
	x float64
	y float64
}

type Circle struct {
	radius float64
	center Point
}

func main() {
	p1 := &Point{y: 3}
	c1 := Circle{4.56, *p1}
	fmt.Println(c1)
	fmt.Println(p1.x, p1.y)
	fmt.Println(c1.center.x)
}
           

output:

{4.56 {0 3}}
0 3
0
           
package main

import "fmt"

type Student struct {
	name   string
	grades []int
	age    int
}

func (s Student) getAge() int {
	return s.age
}

func (s *Student) setAge(age int) {
	(*s).age = age
}

func (s Student) getAverageGrade() float64 {
	sum := 0
	for _, v := range s.grades {
		sum += v
	}
	return float64(sum) / float64(len(s.grades))
}

func (s *Student) getMaxGrade() int {
	curMax := 0

	for _, v := range s.grades {
		if v > curMax {
			curMax = v
		}
	}
	return curMax
}

func main() {
	s1 := Student{"Andy", []int{94, 95, 96}, 20}
	fmt.Println(s1)
	s1.setAge(9)
	fmt.Println(s1)
	fmt.Println(s1.getAverageGrade())
	fmt.Println(s1.getMaxGrade())
}
           

output:

{Andy [94 95 96] 20}
{Andy [94 95 96] 9}
95
96
           

接口

package main

import (
	"fmt"
	"math"
)

type shape interface {
	area() float64
}

type circle struct {
	radius float64
}

type rect struct {
	width  float64
	height float64
}

func (r rect) area() float64 {
	return r.width * r.height
}

func (c circle) area() float64 {
	return math.Pi * c.radius * c.radius
}

func getArea(s shape) float64 {
	return s.area()
}

func main() {
	c1 := circle{4.5}
	r1 := rect{5, 7}
	shapes := []shape{c1, r1}

	for _, shape := range shapes {
		fmt.Println(getArea(shape))
	}
}
           

output:

63.61725123519331
35
           

Beego初步探索

參考視訊資料: Go語言web架構Beego

簡單小例子

首先,配置好代理。然後建立一個檔案夾,用vscode打開,建立一個檔案main.go, 在main.go添加一下代碼:

package main

import (
	"github.com/astaxie/beego"

	"github.com/astaxie/beego/context"
)

func main() {
}
           

然後再終端中輸入

go mod init 【随便起個名字】
           

比如 go mod init mybeegotest

,然後輸入

go tidy
           
go download
           

此時項目結構如下:

Go語言學習心路

輸入一下代碼即完成第一個beego應用啦

package main

import (
   "github.com/astaxie/beego"

   "github.com/astaxie/beego/context"
)

func main() {

   beego.Get("/", func(context *context.Context) {
   	context.Output.Body([]byte("<h1>hello beego</h1>"))
   })

   beego.Get("/hello", func(c *context.Context) {
   	type Person struct {
   		Name string
   	}
   	c.Output.JSON(&Person{Name: "hello from json"}, true, true)
   })

   beego.Run("localhost:8089")
}
           

然後控制台輸入下列指令即可運作。

go run main.cpp
           

在浏覽器輸入 http://127.0.0.1:8089 或 http://127.0.0.1:8089/hello 可以看到傳回結果。

MVC

當然,我們實際開發肯定不會這麼搞,一般會分離資料,邏輯和頁面,這裡采取MVC的模式重構一下。

Go語言學習心路

在項目更目錄建立一個views的檔案夾, 并建立一個名為main.html的檔案(不一定叫main, 也可以其他,與下面綁定模闆的地方對應即可)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Beego</title>
</head>
<body>
    <h1>beego hello world</h1>
</body>
</html>
           

main.go 修改為:

package main

import (
	// 這樣會運作routers包下面的預設方法 init方法
	_ "beegotest/routers"

	"github.com/astaxie/beego"
)

func main() {
	beego.Run()
}
           

建立一個conf目錄, 在該目錄下建立一個app.conf檔案, 這個是配置檔案

appname = mybeegotest
runmode = dev

[dev]
httpport = 8089
           

建立一個routers目錄,在該目錄下建立一個routers.go檔案,這個是路由檔案

package routers

import (
	"beegotest/controllers"

	"github.com/astaxie/beego"
)

func init() {
	// get方法: controllers中的Get函數
	beego.Router("/", &controllers.MainController{}, "get:Get")
}
           

建立一個controllers目錄,在該目錄下建立一個default.go檔案,這個是控制器檔案

package controllers

import "github.com/astaxie/beego"

type MainController struct {
	beego.Controller // 繼承 Controller interface
}

func (m *MainController) Get() {
	m.TplName = "main.html"
}
           

這裡暫時沒有models的案例,關于這個可以檢視這個視訊 (别的up主上傳的,不一定會一直存在,個人感覺, 是以無法保證連接配接永久有效):

GO語言爬蟲實戰項目+Beego架構

我覺得上面那個連結的視訊隻要看下面幾個就夠了:

Go語言學習心路