Windows下Golang初学乍到

发布于:2024-04-26 ⋅ 阅读:(22) ⋅ 点赞:(0)

安装

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

根据系统类型下载即可!

配置

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

开发工具

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

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

了解基本语法

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

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

Web框架

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

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

$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/iris/v12@latest

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

go env -w GOPROXY=https://goproxy.io,direct

go clean --modcache

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

完整示例代码

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!


网站公告

今日签到

点亮在社区的每一天
去签到