[js go]hello gin

133 阅读1分钟

gin是一个go的web框架

安装gin

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

第一个gin接口

	r := gin.Default() // 使用默认配置
	r.GET("/ping", func(c *gin.Context) {
		// c.JSON:返回JSON格式的数据
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
    r.Run() // 启动

请求测试

RESTful风格

	r.GET("/devbro", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "GET",
		})
	})

	r.POST("/devbro", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "POST",
		})
	})

	r.PUT("/devbro", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "PUT",
		})
	})

	r.DELETE("/devbro", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "DELETE",
		})
	})

请求测试 查看日志

静态资源服务

r.Static("/static", "./static")

请求测试 查看日志

返回json字符串

	r.GET("/json", func(c *gin.Context){
		var msg struct {
			Name string `json:"name"`
			Age int `json:"age"`
		}
		msg.Name = "devbro"
		msg.Age = 35

		c.JSON(http.StatusOK, msg)
	})

请求测试

解析查询字符串

使用gin上下文的Query方法

	r.GET("/search", func (c *gin.Context) {
		name := c.Query("name")
		age := c.DefaultQuery("age", "35") // 默认值
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age": age,
		})
	})

解析path参数

使用gin上下文的Param方法

	r.GET("/path/:name/:age", func(c *gin.Context){
		name := c.Param("name")
		age := c.Param("age")
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age": age,
		})
	})