Windows下Golang初学乍到

安装

没啥说的,官网下载即可,地址:All releases - The Go Programming Language

根据系统类型下载即可!

配置

Windows下安装完后,发现path中已经有了,但为了避免可能的问题,还是建议配置GOPATH的。

开发工具

Java出身,IDEA才是最强大的!

给IDEA装上插件,插上飞翔的翅膀!

了解基本语法

找了个教程,地址:《Go 入门指南》 | Go 技术论坛

说实话,又丑又长,真是难以下咽,看了一部分,还是直接上手来得快!

Web框架

作后端出身的,Web框架是少不了的,经过了解发现 Iris 应该是当下功能最全、最热的Web框架了吧,那就学它!

使用以下命令创建并初始化项目:

bash 复制代码
$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/iris/v12@latest

报错则需要先执行下面命令:

bash 复制代码
go env -w GOPROXY=https://goproxy.io,direct

go clean --modcache

官方把 import 与 示例代码分开了,需要细心,不然,代码一片飘红!

完整示例代码

Go 复制代码
package main

import "github.com/kataras/iris/v12"

func main() {
	app := iris.New()

	booksAPI := app.Party("/books")
	{
		booksAPI.Use(iris.Compression)

		// GET: http://localhost:8080/books
		booksAPI.Get("/", list)
		// POST: http://localhost:8080/books
		booksAPI.Post("/", create)
	}

	app.Listen(":8080")
}

// Book example.
type Book struct {
	Title string `json:"title"`
}

func list(ctx iris.Context) {
	books := []Book{
		{"Mastering Concurrency in Go"},
		{"Go Design Patterns"},
		{"Black Hat Go"},
	}

	ctx.JSON(books)
	// TIP: negotiate the response between server's prioritizes
	// and client's requirements, instead of ctx.JSON:
	// ctx.Negotiation().JSON().MsgPack().Protobuf()
	// ctx.Negotiate(books)
}

func create(ctx iris.Context) {
	var b Book
	err := ctx.ReadJSON(&b)
	// TIP: use ctx.ReadBody(&b) to bind
	// any type of incoming data instead.
	if err != nil {
		ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
			Title("Book creation failure").DetailErr(err))
		// TIP: use ctx.StopWithError(code, err) when only
		// plain text responses are expected on errors.
		return
	}

	println("Received Book: " + b.Title)

	ctx.StatusCode(iris.StatusCreated)
}

运行Demo

点击这两个地方都行,也可使用命令行或快捷键,看个人喜好。

成功启动:

访问下试试:

访问地址:http://localhost:8080/books

结果:

The end!

相关推荐
leaves falling7 分钟前
C语言内存函数-
c语言·开发语言
至为芯2 小时前
IP6537至为芯支持双C口快充输出的45W降压SOC芯片
c语言·开发语言
小羊羊Python2 小时前
SoundMaze v1.0.1正式发布!
开发语言·c++
浩瀚地学2 小时前
【Java】JDK8的一些新特性
java·开发语言·经验分享·笔记·学习
l1t2 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
XXOOXRT3 小时前
基于SpringBoot的加法计算器
java·spring boot·后端·html5
yugi9878384 小时前
基于遗传算法优化主动悬架模糊控制的Matlab实现
开发语言·matlab
moxiaoran57534 小时前
Go语言的错误处理
开发语言·后端·golang
yugi9878385 小时前
MATLAB的多层感知器(MLP)与极限学习机(ELM)实现
开发语言·matlab
Never_Satisfied5 小时前
C#获取汉字拼音字母方法总结
开发语言·c#