golang入门记录

参考:
https://www.runoob.com/go/go-tutorial.html
https://zhuanlan.zhihu.com/p/63310903

下载安装包:
windows:https://dl.google.com/go/go1.20.2.windows-amd64.msi

对基础设施,包括跨操作系统、网络、多线程,web、cli都比较好用

Go 语言从发布 1.0 版本以来备受众多开发者关注并得到广泛使用,Go 语言的简单、高效、并发特性吸引了众多传统语言开发者的加入,而且人数越来越多。

作用

鉴于Go语言的特点和设计的初衷,

Go语言作为服务器编程语言,很适合处理日志、数据打包、虚拟机处理、文件系统、分布式系统、数据库代理等;

网络编程方面,Go语言广泛应用于Web 应用、API应用、下载应用等;

除此之外,Go语言还适用于内存数据库和云平台领域,目前国外很多云平台都是采用Go开发。

  • 服务器编程,以前你如果使用C或者C++做的那些事情,用Go来做很合适,例如处理日志、数据打包、虚拟机处理、文件系统等。
    分布式系统、数据库代理器、中间件等,例如Etcd。
  • 网络编程,这一块目前应用最广,包括Web应用、API应用、下载应用,而且Go内置的net/http包基本上把我们平常用到的网络功能都实现了。
  • 数据库操作
    开发云平台,目前国外很多云平台在采用Go开发

开始使用

hello world

package main

//import 语句中并不是引入目录,而是引入指定包的 path
import "fmt"

//fmt包 包括了 格式化文本,打印到康之泰

import "fmt"
//运行main包时自动执行main函数

func main() {
    
    
    fmt.Println("Hello, World!")
}

使用第三方包

找包:https://pkg.go.dev/

go mod init go_test

go mod init 是 Go Modules 的命令之一,它的作用是将当前目录初始化为一个新的 Go 模块,并在当前目录中生成一个 go.mod 文件。该文件是一个纯文本文件,其中包含用于管理模块依赖关系的信息,例如模块名称、版本和所需的依赖项等。

 go mod tidy

使用 go mod tidy 命令来自动清理不需要的依赖项;使用 go mod download 命令来下载一组特定的依赖项;使用 go mod vendor 命令将依赖项复制到当前目录的 vendor 目录中等等。通过使用这些命令,开发者可以更轻松地管理 Go 模块和依赖项。
在这里插入图片描述
解决golang提示dial tcp 172.217.160.113:443: connectex: A connection attempt failed

 go env -w GOPROXY=https://goproxy.cn

在这里插入图片描述

使用自己创建的第三方包

创建greeting文件

go mod init greeting

package greetings

import "fmt"

func Hello(name string) string {
    
    
	message := fmt.Sprintf("Hi,%v Welcome!", name)
	// := 是声明初始化变量简写
	return message
}


由于没有发布模块,将包替换为本地路径

go mod edit -replace example.com/greetings=./greetings

在这里插入图片描述

在这里插入图片描述

web-service-gin

Gin 简化了许多与构建 Web 应用程序相关的编码任务,包括 Web 服务

目标,创建接口
/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运行

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

完整代码:

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.
}

如何写go

介绍

go tool, fetch, build, 安装 Go modules, packages, commands 标准方法

代码架构

it’s a good habit to organize your code as if you will publish it someday

程序

编译和运行一个程序
1.choose a module path (we’ll use example.com/user/hello) and create a go.mod file that declares it

源代码第一句package name,

build ,install 程序

go install xxx

该命令产生可一个可执行二进制文件在$HOME/go/bin/hello ( Windows, %USERPROFILE%\go\bin\xxx.exe).

安装目录由 GOPATH ,GOBIN/bin环境变量控制。
可以用go env 命令设置值

go env -w GOBIN=/somewhere/else/bin
go env -u GOBIN

在这里插入图片描述
下载的包在 Go安装目录\bin\pkg\mod

Go旅程

1.基础语法 数据结构
ps:
:= 是 Go 语言里的一个声明语句,用于定义并初始化一个新的变量。它会根据变量值的类型来自动推断该变量的类型,在函数外不可定义

类型放在后面定义

字符串用双引号

2.方法 接口

方法只是一个接受receiver参数的函数

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并发特性

https://tour.go-zh.org/welcome/1

猜你喜欢

转载自blog.csdn.net/weixin_38235865/article/details/129531086
今日推荐