Goland—学习使用后端微服务框架—GIN—学习笔记

为什么用gin?

参考文档:

简介 · Go语言中文文档 (topgoer.com)

一、框架初体验

跑个见面代码:Hello,World

1、下载模块

go get -u github.com/gin-gonic/gin

2、代码:

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	// 1.创建路由
	r := gin.Default()
	// 2.绑定路由规则,执行的函数
	// gin.Context,封装了request和response
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})
	// 3.监听端口,默认在8080
	// Run("里面不指定端口号默认为8080")
	r.Run(":8000")
}

3、通过8080端口打开本地网址:

http://localhost:8000/

 输出:

 二、路由器说明

gin 框架中采用的路由库是基于httprouter做的。

1、阅读文档

GitHub - julienschmidt/httprouter:一款高性能的 HTTP 请求路由器,可很好地扩展

 

 2、运行示例

package main

import (
    "fmt"
    "net/http"
    "log"

    "github.com/julienschmidt/httprouter"
)
//网页上输出welcome
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}
//网页上输出hello,xxx(xxx是/后面的路径名)
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

上面主要是实现路由转换的例子,输入相应的路径会打开相应的网址,接下来我们需要进行gin和gorm框架的整合。下一步会学习整合Vue框架,最后实现本项目。

猜你喜欢

转载自blog.csdn.net/qq_51701007/article/details/125025038