Reference:
https://www.runoob.com/go/go-tutorial.html
https://zhuanlan.zhihu.com/p/63310903
Download the installation package:
windows: https://dl.google.com/go/go1.20.2.windows-amd64.msi
It is easy to use for infrastructure, including cross-operating system, network, multi-thread, web and cli
Since the release of version 1.0, the Go language has attracted the attention of many developers and has been widely used. The simplicity, efficiency, and concurrent features of the Go language have attracted many traditional language developers to join, and the number is increasing.
effect
In view of the characteristics of the Go language and the original intention of the design,
As a server programming language , Go language is very suitable for processing logs, data packaging, virtual machine processing, file systems, distributed systems, database agents, etc.;
In terms of network programming , the Go language is widely used in Web applications, API applications, download applications, etc.;
In addition, the Go language is also suitable for in-memory databases and cloud platforms . At present, many cloud platforms abroad are developed using Go.
- For server programming, if you used C or C++ to do those things in the past, it is very suitable to use Go to do them, such as processing logs, data packaging, virtual machine processing, file systems, etc.
Distributed systems, database proxies, middleware, etc., such as Etcd. - Network programming is currently the most widely used, including Web applications, API applications, and download applications, and the built-in net/http package in Go basically realizes all the network functions we usually use.
- Database operation
Develop cloud platform, currently many cloud platforms abroad are using Go development
start using
hello world
package main
//import 语句中并不是引入目录,而是引入指定包的 path
import "fmt"
//fmt包 包括了 格式化文本,打印到康之泰
import "fmt"
//运行main包时自动执行main函数
func main() {
fmt.Println("Hello, World!")
}
Use third-party packages
Find the package: https://pkg.go.dev/
go mod init go_test
go mod init is one of the commands of Go Modules. Its function is to initialize the current directory as a new Go module and generate a go.mod file in the current directory. This file is a plain text file that contains information for managing module dependencies, such as module name, version, and required dependencies.
go mod tidy
Use the go mod tidy command to automatically clean up unneeded dependencies; use the go mod download command to download a specific set of dependencies; use the go mod vendor command to copy dependencies into the vendor directory of the current directory; and so on. By using these commands, developers can more easily manage Go modules and dependencies.
Solve golang prompt dial tcp 172.217.160.113:443: connectex: A connection attempt failed
go env -w GOPROXY=https://goproxy.cn
Use third-party packages you create yourself
Create a greeting file
go mod init greeting
package greetings
import "fmt"
func Hello(name string) string {
message := fmt.Sprintf("Hi,%v Welcome!", name)
// := 是声明初始化变量简写
return message
}
In
replace the package with the local path since the module is not published
go mod edit -replace example.com/greetings=./greetings
web-service-gin
Gin simplifies many coding tasks associated with building web applications, including web services
target, create interface
/albums
- GET – Get a list of all albums, returned as JSON.
- POST – Add a new album from request data sent as JSON.
/albums/:id
- GET – Get an album by its ID, returning the album data as JSON.
get
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// album represents data about a record album.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// albums slice to seed record album data.
var albums = []album{
{
ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{
ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{
ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
c.IndentedJSON(http.StatusOK, albums)
}
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.Run("localhost:8080")
}
cmd run
curl http://localhost:8080/albums --header "Content-Type: application/json" --request "GET"
post
curl http://localhost:8080/albums --include --header "Content-Type: application/json" --request "POST" --data '{"id": "4", "title": "The Modern Sound of Betty Carter", "artist": "Betty Carter", "price": 49.99}'
get id
curl http://localhost:8080/albums/4 #4是id
Full code:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// album represents data about a record album.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// albums slice to seed record album data.
var albums = []album{
{
ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{
ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{
ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
// Context.IndentedJSON to serialize the struct into JSON and add it to the response
c.IndentedJSON(http.StatusOK, albums)
}
// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
var newAlbum album
// Call BindJSON to bind the received JSON to
// newAlbum.
if err := c.BindJSON(&newAlbum); err != nil {
return
}
// Add the new album to the slice.
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
id := c.Param("id")
// Loop over the list of albums, looking for
// an album whose ID value matches the parameter.
for _, a := range albums {
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{
"message": "album not found"})
}
func main() {
router := gin.Default()
//Initialize a Gin router
router.GET("/albums", getAlbums)
//associate the GET HTTP method and /albums path with a handler function.
router.POST("/albums", postAlbums)
router.GET("/albums/:id", getAlbumByID)
router.Run("localhost:8080")
//attach the router to an http.Server and start the server.
}
how to write go
introduce
go tool, fetch, build, install Go modules, packages, commands standard way
code structure
it’s a good habit to organize your code as if you will publish it someday
program
Compile and run a program
1.choose a module path (we'll use example.com/user/hello) and create a go.mod file that declares it
The first sentence of the source code package name,
build, install program
go install xxx
This command produces an executable binary file in $HOME/go/bin/hello (Windows, %USERPROFILE%\go\bin\xxx.exe).
The installation directory is controlled by the GOPATH, GOBIN/bin environment variables.
Values can be set with the go env command
go env -w GOBIN=/somewhere/else/bin
go env -u GOBIN
The downloaded package is in Go installation directory \bin\pkg\mod
Gojourney
1. Basic grammatical data structure
ps:
:= is a declaration statement in Go language, used to define and initialize a new variable. It will automatically infer the type of the variable according to the type of the variable value, which cannot be defined outside the function
The type is defined later
Strings with double quotes
2. Method interface
A method is just a function that accepts a receiver parameter
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{
3, 4}
fmt.Println(v.Abs())
}
3. concurrency primitives concurrency features