GO学习笔记

环境变量配置

GoROOT是go的安装包,GOPATH是项目路径,比如hello.go所在项目的路径

 

工程结构是

project

  bin

  pkg

  src

    main.go

bin是输出目录,src是工作目录

代码里注意package main

1 package main
2 
3 import "fmt"
4 
5 func main() {
6     fmt.Println("你好呀")
7 }
8 
9 // bin包含编译后的代码、pkg包含包对象、src中包含Go源文件。
main.go

编辑配置里注意

运行种类是目录,路径是绝对路径src

安装gin框架

 

go env -w GO111MODULE=on
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct

go get -u github.com/gin-gonic/gin
 1 package main
 2 
 3 import (
 4     "net/http"
 5 
 6     "github.com/gin-gonic/gin"
 7 )
 8 
 9 func main() {
10     // 1.创建路由
11    r := gin.Default()
12    // 2.绑定路由规则,执行的函数
13    // gin.Context,封装了request和response
14    r.GET("/", func(c *gin.Context) {
15       c.String(http.StatusOK, "hello World!")
16    })
17    // 3.监听端口,默认在8080
18    // Run("里面不指定端口号默认为8080") 
19    r.Run(":8080")
20 }

 

 安装go-redis

go get github.com/garyburd/redigo/redis
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "github.com/garyburd/redigo/redis"
 6 )
 7 
 8 func main() {
 9     c, err := redis.Dial("tcp", "localhost:6379")
10     if err != nil {
11         fmt.Println("conn redis failed,", err)
12         return
13     }
14 
15     fmt.Println("redis conn success")
16 
17     defer c.Close()
18 }

 在此之前还得先本机装redis服务

 https://github.com/MicrosoftArchive/redis/releases

下载zip解压好,运行  redis-server.exe 

此时再跑go程序,输出redis conn success

这么理解吧,GitHub安装的redigo只是提供操作redis的接口,但是redis是类似MySQL,nginx一样的服务,需要本机下载运行这个服务。也就是需要两步操作。

安装GORM(Object Relational Mapping)GORM 官方支持的数据库类型有: MySQL, PostgreSQL, SQlite, SQL Server

go get -u github.com/jinzhu/gorm
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "github.com/jinzhu/gorm"
 6     _ "github.com/jinzhu/gorm/dialects/sqlite"
 7 )
 8 
 9 type Product struct {
10     gorm.Model
11     Code  string
12     Price uint
13 }
14 
15 func main() {
16     db, err := gorm.Open("sqlite3", "test.db")
17     if err != nil {
18         panic("failed to connect database")
19     }
20     defer db.Close()
21     fmt.Println("connect sqlite3 success")
22     //自动检查 Product 结构是否变化,变化则进行迁移
23     db.AutoMigrate(&Product{})
24 
25     //
26     db.Create(&Product{Code: "L1212", Price: 1000})
27 
28     //
29     var product Product
30     db.First(&product, 1)                   // 找到id为1的产品
31     db.First(&product, "code = ?", "L1212") // 找出 code 为 l1212 的产品
32 
33     // 改 - 更新产品的价格为 2000
34     db.Model(&product).Update("Price", 2000)
35 
36     // 删 - 删除产品
37     db.Delete(&product)
38 }
View Code

碰到错误

missing go.sum entry for module providing package (当在代码中使用了第三方库 ,但是go.mod中并没有跟着更新的时候如果直接run或者build就会报这个错误)

解决方法

go mod tidy

这个命令会:

删除不需要的依赖包

下载新的依赖包

更新go.sum

至此,程序没错误,但是sqlite数据库服务还没装,安装sqlite

https://blog.csdn.net/Ellen5203/article/details/90547657

go get github.com/go-sql-driver/mysql

go-sql-driver 是go用来链接mysql数据库的包。

sqlite数据库轻量级,它就在工程里面!,GoLand这个软件右边导航栏数据库点开就看到了,左边项目文件,在src里,test.db。

posted @ 2022-04-29 12:01  剩下的交给时间就好  阅读(45)  评论(0编辑  收藏  举报