Go语言GIN框架安装与入门

news2024/9/24 21:17:41

Go语言GIN框架安装与入门

文章目录

  • Go语言GIN框架安装与入门
    • 1. 创建配置环境
    • 2. 配置环境
    • 3. 下载最新版本Gin
    • 4. 编写第一个接口
    • 5. 静态页面和资源文件加载
    • 6. 各种传参方式
      • 6.1 URL传参
      • 6.2 路由形式传参
      • 6.3 前端给后端传递JSON格式
      • 6.4 表单形式传参
    • 7. 路由和路由组
    • 8. 项目代码main.go
    • 9. 总结

之前学习了一周的GO语言,学会了GO语言基础,现在尝试使用GO语言最火的框架GIN来写一些简单的接口。看了B站狂神说的GIN入门视频,基本明白如何写接口了,下面记录一下基本的步骤。

1. 创建配置环境

我们使用Goland创建第一个新的开发环境,这里只要在windows下面安装好Go语言,Goroot都能自动识别。
在这里插入图片描述
新的项目也就只有1个go.mod的文件,用来表明项目中使用到的第三方库。
在这里插入图片描述

2. 配置环境

我们使用第三方库是需要从github下载的,但是github会经常连不上,所以我们就需要先配置第三方的代理地址。我们再Settings->Go->Go Modules->Environment下面配上代理地址。

GOPROXY=https://goproxy.cn,direct

在这里插入图片描述

3. 下载最新版本Gin

在IDE里面的Terminal下面安装Gin框架,使用下面的命令安装Gin,安装完成以后,go.mod下面require就会自动添加依赖。

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

在这里插入图片描述

4. 编写第一个接口

创建main.go文件,然后编写以下代码,这里定义了一个/hello的路由。

package main

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

func main() {

	ginServer := gin.Default()
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "hello world"})
	})

	ginServer.Run(":8888")

}

编译运行通过浏览器访问,就可以输出JSON。

在这里插入图片描述

5. 静态页面和资源文件加载

使用下面代码加入项目下面的静态页面(HTML文件),以及动态资源(JS)。

	// 加载静态页面
	ginSever.LoadHTMLGlob("templates/*")

	// 加载资源文件
	ginSever.Static("/static", "./static")

这是项目的资源文件列表
在这里插入图片描述
其中index.html文件如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的第一个GO web页面</title>
    <link rel="stylesheet" href="/static/css/style.css">
    <script src="/static/js/common.js"></script>
</head>
<body>

<h1>谢谢大家支持</h1>

获取后端的数据为:
{{.msg}}

<form action="/user/add" method="post">
        <p>username: <input type="text" name="username"></p>
        <p>password: <input type="text" name="password"></p>
        <button type="submit"> 提 交 </button>
</form>


</body>
</html>

接着就可以响应一个页面给前端了。

	// 响应一个页面给前端
	ginSever.GET("/index", func(context *gin.Context) {
		context.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "这是go后台传递来的数据",
		})
	})

在这里插入图片描述

6. 各种传参方式

6.1 URL传参

在后端获取URL传递来的参数。

	// 传参方式
	//http://localhost:8082/user/info?userid=123&username=dfa
	ginSever.GET("/user/info", myHandler(), func(context *gin.Context) {
		// 取出中间件中的值
		usersession := context.MustGet("usersession").(string)
		log.Println("==========>", usersession)

		userid := context.Query("userid")
		username := context.Query("username")
		context.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})

其中上面多加了一个中间键,就是接口代码运行之前执行的代码,myHandler的定义如下:

// go自定义中间件
func myHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 设置值,后续可以拿到
		context.Set("usersession", "userid-1")
		context.Next() // 放行
	}
}

6.2 路由形式传参

	// http://localhost:8082/user/info/123/dfa
	ginSever.GET("/user/info/:userid/:username", func(context *gin.Context) {
		userid := context.Param("userid")
		username := context.Param("username")
		context.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})

6.3 前端给后端传递JSON格式

	// 前端给后端传递json
	ginSever.POST("/json", func(context *gin.Context) {
		// request.body
		data, _ := context.GetRawData()
		var m map[string]interface{}
		_ = json.Unmarshal(data, &m)
		context.JSON(http.StatusOK, m)

	})

6.4 表单形式传参

	ginSever.POST("/user/add", func(context *gin.Context) {
		username := context.PostForm("username")
		password := context.PostForm("password")
		context.JSON(http.StatusOK, gin.H{
			"msg":      "ok",
			"username": username,
			"password": password,
		})
	})

7. 路由和路由组

	// 路由
	ginSever.GET("/test", func(context *gin.Context) {
		context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	})

	// 404
	ginSever.NoRoute(func(context *gin.Context) {
		context.HTML(http.StatusNotFound, "404.html", nil)
	})

	// 路由组
	userGroup := ginSever.Group("/user")
	{
		userGroup.GET("/add")
		userGroup.POST("/login")
		userGroup.POST("/logout")
	}

	orderGroup := ginSever.Group("/order")
	{
		orderGroup.GET("/add")
		orderGroup.DELETE("delete")
	}

8. 项目代码main.go

package main

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

// go自定义中间件
func myHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 设置值,后续可以拿到
		context.Set("usersession", "userid-1")
		context.Next() // 放行
	}
}

func main() {
	// 创建一个服务
	ginSever := gin.Default()
	//ginSever.Use(favicon.New("./icon.png"))

	// 加载静态页面
	ginSever.LoadHTMLGlob("templates/*")

	// 加载资源文件
	ginSever.Static("/static", "./static")

	//ginSever.GET("/hello", func(context *gin.Context) {
	//	context.JSON(200, gin.H{"msg": "hello world"})
	//})
	//ginSever.POST("/user", func(c *gin.Context) {
	//	c.JSON(200, gin.H{"msg": "post,user"})
	//})
	//ginSever.PUT("/user")
	//ginSever.DELETE("/user")

	// 响应一个页面给前端
	ginSever.GET("/index", func(context *gin.Context) {
		context.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "这是go后台传递来的数据",
		})
	})

	// 传参方式
	//http://localhost:8082/user/info?userid=123&username=dfa
	ginSever.GET("/user/info", myHandler(), func(context *gin.Context) {
		// 取出中间件中的值
		usersession := context.MustGet("usersession").(string)
		log.Println("==========>", usersession)

		userid := context.Query("userid")
		username := context.Query("username")
		context.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})

	// http://localhost:8082/user/info/123/dfa
	ginSever.GET("/user/info/:userid/:username", func(context *gin.Context) {
		userid := context.Param("userid")
		username := context.Param("username")
		context.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})

	// 前端给后端传递json
	ginSever.POST("/json", func(context *gin.Context) {
		// request.body
		data, _ := context.GetRawData()
		var m map[string]interface{}
		_ = json.Unmarshal(data, &m)
		context.JSON(http.StatusOK, m)

	})

	// 表单
	ginSever.POST("/user/add", func(context *gin.Context) {
		username := context.PostForm("username")
		password := context.PostForm("password")
		context.JSON(http.StatusOK, gin.H{
			"msg":      "ok",
			"username": username,
			"password": password,
		})
	})

	// 路由
	ginSever.GET("/test", func(context *gin.Context) {
		context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	})

	// 404
	ginSever.NoRoute(func(context *gin.Context) {
		context.HTML(http.StatusNotFound, "404.html", nil)
	})

	// 路由组
	userGroup := ginSever.Group("/user")
	{
		userGroup.GET("/add")
		userGroup.POST("/login")
		userGroup.POST("/logout")
	}

	orderGroup := ginSever.Group("/order")
	{
		orderGroup.GET("/add")
		orderGroup.DELETE("delete")
	}

	// 端口
	ginSever.Run(":8888")

}

9. 总结

以上就是Gin入门的所有内容了,大家觉得还有帮助,欢迎点赞收藏哦。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/890265.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

KBEngine增加ThinkingData打点

Windows下的安装ThinkingData 首先根据他的文档&#xff0c;安装sdk和Logbus&#xff0c;他的原理是sdk写入到log文件&#xff0c;然后通过Logbus2来传送到TD&#xff08;ThinkingData&#xff09;服务器。 通过pip获取 Python SDK pip install ThinkingDataSdk pip install…

力扣75——多维动态规划

总结leetcode75中的多维动态规划算法题解题思路。 上一篇&#xff1a;力扣75——一维动态规划 力扣75——多维动态规划 1 不同路径2 最长公共子序列3 买卖股票的最佳时机含手续费4 编辑距离1 - 4 解题总结 1 不同路径 题目&#xff1a; 一个机器人位于一个 m x n 网格的左上角…

史上最全!80个数字化工厂常见术语合集,看完秒懂~

这几天&#xff0c;有几个朋友私信我&#xff0c;问了我不少问题&#xff0c;其中有一个让我讲一讲“数字化工厂”方面的知识&#xff0c;了解我的人想必都清楚&#xff0c;我这个人一般都是有求必应的。 所以今天来聊一聊“数字化工厂”的常见术语&#xff0c;帮助大家快速搞…

【Linux】模拟实现linux的shell

#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> #define NUM 1024 #define SIZE 32 #define SEP " " int main() {//保存输入后的字符串char …

你需要需求管理解决方案的三个原因

我们最近研究了一份 Forrester Research 的报告&#xff0c;得出如下结论&#xff1a;高度监管的行业可以从敏捷需求管理方法中受益。在本文中&#xff0c;我们将深入探讨所有行业的客户如何从一个协作平台中受益&#xff0c;该平台如何帮助他们在复杂的开发周期中管理需求。 …

【傅里叶级数与傅里叶变换】数学推导——3、[Part4:傅里叶级数的复数形式] + [Part5:从傅里叶级数推导傅里叶变换] + 总结

文章内容来自DR_CAN关于傅里叶变换的视频&#xff0c;本篇文章提供了一些基础知识点&#xff0c;比如三角函数常用的导数、三角函数换算公式等。 文章全部链接&#xff1a; 基础知识点 Part1&#xff1a;三角函数系的正交性 Part2&#xff1a;T2π的周期函数的傅里叶级数展开 P…

工作流引擎之Flowable教程(整合SpringBoot)

简介 Flowable是什么&#xff0c;下面是官方文档介绍&#xff1a; Flowable是一个使用Java编写的轻量级业务流程引擎。Flowable流程引擎可用于部署BPMN 2.0流程定义&#xff08;用于定义流程的行业XML标准&#xff09;&#xff0c; 创建这些流程定义的流程实例&#xff0c;进行…

C++新经典04--位运算

背景 许多网络游戏为了刺激玩家每天上线&#xff0c;都在游戏中设有“每日任务”——每天让玩家做一些任务&#xff0c;如杀怪、采集来赚取积分、金钱、经验等。每日任务根据游戏不同&#xff0c;数量也不同&#xff0c;每日任务比较少的网络游戏中&#xff0c;可能每日任务只…

多语言多模态(融合图像和文本)大模型-mPLUG-Owl论文解读

近期复现了mPLUG-Owl&#xff0c;效果提升了好几个点&#xff0c;特来精读一番&#xff1a;感谢大佬们的工作&#xff1a; 论文名称&#xff1a;mPLUG-Owl: Modularization Empowers Large Language Models with Multimodality 论文地址&#xff1a;https://arxiv.org/pdf/23…

使用GUI Guider工具开发嵌入式GUI应用(5)-使用timer对象显示动画

使用GUI Guider工具开发嵌入式GUI应用&#xff08;5&#xff09;-使用timer对象显示动画 文章目录 使用GUI Guider工具开发嵌入式GUI应用&#xff08;5&#xff09;-使用timer对象显示动画引言LVGL中的timer对象基于timer对象实现仪表走针小结 引言 设计GUI的显示元素动起来&a…

Websocket原理和实践

一、概述 1.websocket是什么&#xff1f; WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单&#xff0c;允许服务端主动向客户端推送数据。在WebSocket API中&#xff0c;浏览器和服务器只需要完成一次握手&…

如何快速优化 CnosDB 数据库性能与延迟:使用 Jaeger 分布式追踪系统

在正式的生产环境中&#xff0c;数据库的性能和延迟对于确保系统的稳定和高效运行至关重要。特别是在与 CnosDB 数据库进行交互时&#xff0c;更深入地了解其表现变得尤为重要。这时Jaeger 分布式追踪系统发挥了巨大的作用。在本篇博客中&#xff0c;我们将深入探讨如何通过使用…

ATA-4000系列高压功率放大器——应用场景介绍

ATA-4000系列是一款理想的可放大交、直流信号的高压功率放大器。最大输出310Vp-p(155Vp)电压&#xff0c;452Wp功率&#xff0c;可以驱动高压功率型负载。电压增益&#xff0c;直流偏置数控精细可调&#xff0c;为客户提供了丰富的测试选择。 图&#xff1a;ATA-4000系列高压功…

ndk开发-交叉编译

为什么要使用交叉编译&#xff1a; 在linux系统一般使用c c编译可执行程序或者so库文件。该程序只能在当前linux系统执行&#xff0c;为了将生成文件可以再android平台运行&#xff0c;必须使用交叉编译。ndk中提供了跟多android平台交叉编译链&#xff0c;所以首先下载ndk工具…

FPGA应用学习笔记-----布图布线

分割可以将运行时间惊人地减少到三个小时更小的布局布线操作&#xff0c;主要的结构不影响另一个&#xff01;和增量设计流程一样 关键路径布图&#xff1a; 对于不同的模块有不同的电路和不同的关键路径&#xff0c; 布图没有主要的分割&#xff0c;布图由两个小的区域组成&a…

KDD 2023 获奖论文公布,港中文、港科大等获最佳论文奖

ACM SIGKDD&#xff08;国际数据挖掘与知识发现大会&#xff0c;KDD&#xff09;是数据挖掘领域历史最悠久、规模最大的国际顶级学术会议&#xff0c;也是首个引入大数据、数据科学、预测分析、众包等概念的会议。 今年&#xff0c;第29届 KDD 大会于上周在美国加州长滩圆满结…

C语言入门教程,C语言学习教程(非常详细)第五章 循环结构与选择结构

C语言if else语句详解 前面我们看到的代码都是顺序执行的&#xff0c;也就是先执行第一条语句&#xff0c;然后是第二条、第三条……一直到最后一条语句&#xff0c;这称为顺序结构。 但是对于很多情况&#xff0c;顺序结构的代码是远远不够的&#xff0c;比如一个程序限制了只…

【Javaswing课设源码】学生信息管理 Mysql课程设计 管理员 教师 学生

文章目录 系统介绍 系统介绍 大学时代弄的一个课设&#xff0c;当时百度[学长敲代码]找的代做&#xff0c;代码思路很清晰&#xff0c;完全按照我的功能需求去做的&#xff0c;主要是价格便宜&#xff0c;真的爱了&#xff0c;现在回头学习也是不错的一个项目。大概内容如下 本…

springboot里 用zxing 生成二维码

引入pom <!--二维码依赖--><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version></dependency><dependency><groupId>com.google.zxing</groupId>…

【分类讨论】CF1674 E

Problem - E - Codeforces 题意&#xff1a; 思路&#xff1a; 样例&#xff1a; 这种分类讨论的题&#xff0c;主要是去看答案的最终来源是哪几种情况&#xff0c;这几种情况得不重不漏 Code&#xff1a; #include <bits/stdc.h>#define int long longusing i64 lon…