gin react_如何使用Go,Gin和React构建Web应用

本文介绍了如何使用Go的Gin框架和React构建一个带有身份验证的Web应用。首先,概述了Gin作为高性能微框架的特性,然后逐步指导读者设置Go环境,构建API,定义路由,以及使用React创建UI。接着,展示了如何使用Auth0进行用户认证,创建API客户端,并保护API端点。最后,通过实现登录和笑话应用功能,将所有组件整合在一起。
摘要由CSDN通过智能技术生成

gin react

by Francis Sunday

弗朗西斯(星期日)

如何使用Go,Gin和React构建Web应用 (How to build a web app with Go, Gin, and React)

This article was originally posted on My Blog

本文最初发布在我的博客上

TL;DR: In this tutorial, I’ll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it. Check out the Github repo for the code we’re going to write.

TL; DR:在本教程中,我将向您展示使用Go和Gin框架构建Web应用程序并向其添加身份验证是多么容易。 查看Github存储 ,了解我们将要编写的代码。

Gin is a high-performance micro-framework. It delivers a very minimalistic framework that carries with it only the most essential features, libraries, and functionalities needed to build web applications and microservices. It makes it simple to build a request handling pipeline from modular, reusable pieces. It does this by allowing you to write middleware that can be plugged into one or more request handlers or groups of request handlers.

杜松子酒是一种高性能的微框架。 它提供了一个非常简约的框架,其中仅包含构建Web应用程序和微服务所需的最基本的功能,库和功能。 它使从模块化,可重用的块构建请求处理管道变得很简单。 通过允许您编写可插入一个或多个请求处理程序或一组请求处理程序的中间件,可以做到这一点。

杜松子酒功能 (Gin features)

Gin is a fast, simple yet fully featured and very efficient web framework for Go. Check out some of the features below that make it a worthy framework to consider for your next Golang project.

Gin是用于Go的快速,简单但功能齐全且非常有效的Web框架。 查看下面的一些功能,这些功能使其成为值得考虑的下一个Golang项目的框架。

  • Speed: Gin is built for speed. The framework offers a Radix tree based routing and small memory footprint. No reflection. Predictable API performance.

    速度:杜松子酒是为了提高速度而设计的。 该框架提供了基于Radix树的路由和较小的内存占用。 没有反思。 可预测的API性能。

  • Crash-Free: Gin has the capability of catching crashes or panics during runtime, and can recover from them. This way your application will always be available.

    无崩溃 :Gin具有在运行时捕获崩溃或紧急事件的功能,并且可以从中恢复。 这样,您的应用程序将始终可用。

  • Routing: Gin provides a routing interface to allow you to express how your web application or API routes should look.

    路由: Gin提供了路由接口,可让您表达Web应用程序或API路由的外观。

  • JSON Validation: Gin can parse and validate JSON requests easily, checking for the existence of required values.

    JSON验证: Gin可以轻松解析和验证JSON请求,检查是否存在必需的值。

  • Error Management: Gin provides a convenient way to collect all the errors occurred during a HTTP request. Eventually, a middleware can write them to a log file or to a database and send them through the network.

    错误管理: Gin提供了一种方便的方法来收集HTTP请求期间发生的所有错误。 最终,中间件可以将它们写入日志文件或数据库中,并通过网络发送它们。

  • Built-In Rendering: Gin provides an easy to use API for JSON, XML, and HTML rendering.

    内置渲染: Gin为JSON,XML和HTML渲染提供了易于使用的API。

先决条件 (Prerequisites)

To follow along with this tutorial, you’ll need to have Go installed on your machine, a web browser to view the app, and a command line to execute build commands.

要跟随本教程的进行,您需要在计算机上安装Go,使用Web浏览器查看应用程序,并使用命令行执行构建命令。

Go, or as its normally called Golang, is a programming language developed by Google for building modern software. Go is a language designed to get stuff done efficiently and quickly. The key benefits of Go include:

Go或通常称为Golang ,是Google为开发现代软件而开发的一种编程语言。 Go是一种旨在高效快速地完成工作的语言。 Go的主要优势包括:

  • Strongly typed and garbage collected

    强类型和垃圾收集
  • Blazing fast compile times

    快速的编译时间
  • Concurrency built in

    内置并发
  • Extensive standard library

    广泛的标准库

Head over to the downloads section of the Go website to get Go running on your machine.

转至Go网站的下载部分 ,以使Go在您的计算机上运行。

使用Gin构建应用 (Building an app with Gin)

We’ll be building a simple joke listing app with Gin. Our app will list some silly dad jokes. We are going to add authentication to it, so that all logged-in users will have the privilege to like and view jokes.

我们将使用Gin构建一个简单的笑话清单应用程序。 我们的应用程序将列出一些愚蠢的爸爸笑话。 我们将向其中添加身份验证,以便所有登录的用户都有权喜欢和查看笑话。

This will allow us illustrate how Gin can be used to develop web applications and/or APIs.

这将使我们能够说明如何使用Gin开发Web应用程序和/或API。

We’ll be making use of the following functionalities offered by Gin:

我们将利用Gin提供的以下功能:

  • Middleware

    中间件
  • Routing

    路由
  • Routes Grouping

    路线分组

预备,准备,开始 (Ready, set, Go)

We will write our entire Go application in a main.go file. Since it’s a small application, it’s going to be easy to build the application with just go run from the terminal.

我们将整个Go应用程序写入main.go文件中。 由于它是一个小型应用程序,因此只需从终端go run即可轻松构建该应用程序。

We’ll create a new directory golang-gin in our Go workspace, and then a main.go file in it:

我们将在Go工作区中创建一个新目录golang-gin ,然后在其中创建一个main.go文件:

$ mkdir -p $GOPATH/src/github.com/user/golang-gin
$ cd $GOPATH/src/github.com/user/golang-gin
$ touch main.go

The content of the main.go file:

main.go文件的内容:

package main

import (
  "net/http"
  
  "github.com/gin-gonic/contrib/static"
  "github.com/gin-gonic/gin"
)

func main() {
  // Set the router as the default one shipped with Gin
  router := gin.Default()
  
  // Serve frontend static files
  router.Use(static.Serve("/", static.LocalFile("./views", true)))
  
  // Setup route group for the API
  api := router.Group("/api")
  {
    api.GET("/", func(c *gin.Context) {
      c.JSON(http.StatusOK, gin.H {
        "message": "pong",
      })
    })
  }
  
  // Start and run the server
  router.Run(":3000")
}

We’ll need to create some more directories for our static files. In the same directory as the main.go file, let's create a views folder. In the views folder, create a js folder and an index.html file in it.

我们需要为静态文件创建更多目录。 在与main.go文件相同的目录中,让我们创建一个views文件夹。 在views文件夹中,创建一个js文件夹和一个index.html文件。

The index.html file will be very simple for now:

现在, index.html文件将非常简单:

<!DOCTYPE html>
<html>
<head>
  <title>Jokeish App</title>
</head>

<body>
  <h1>Welcome to the Jokeish App</h1>
</body>
</html>

Before we test what we have so far, let’s install the added dependencies:

在测试到目前为止我们拥有的东西之前,让我们安装添加的依赖项:

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

To see what’s working, we’ll need to start our server by running go run main.go.

要查看运行情况,我们需要通过运行go run main.go来启动服务器。

Once the application is running, navigate to http://localhost:3000 in your browser. If all went well, you should see level 1 header text Welcome to the Jokeish App displayed.

应用程序运行后,在浏览器中导航到http://localhost:3000 。 如果一切顺利,您应该看到显示的1级标题文本“ 欢迎使用Jokeish App”

定义API (Defining the API)

Let’s add some more code in our main.go file for our API definitions. We'll update our main function with two routes /jokes/ and /jokes/like/:jokeID to the route group /api/.

让我们在main.go文件中为API定义添加更多代码。 我们将使用两个路由/jokes//jokes/like/:jokeID到路由组/api/main函数。

func main() {
  // ... leave the code above untouched...
  
  // Our API will consit of just two routes
  // /jokes - which will retrieve a list of jokes a user can see
  // /jokes/like/:jokeID - which will capture likes sent to a particular joke
  api.GET("/jokes", JokeHandler)
  api.POST("/jokes/like/:jokeID", LikeJoke)
}

// JokeHandler retrieves a list of available jokes
func JokeHandler(c *gin.Context) {
  c.Header("Content-Type", "application/json")
  c.JSON(http.StatusOK, gin.H {
    "message":"Jokes handler not implemented yet",
  })
}

// LikeJoke increments the likes of a particular j
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个完整的基于Gin框架的基本身份验证流程的代码示例: ```go package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { router := gin.Default() // 定义一个验证函数 auth := func(username, password string) bool { // 这里可以根据具体需求进行用户名和密码的验证 return username == "admin" && password == "password" } // 使用BasicAuth中间件,并提供验证函数 router.Use(gin.BasicAuth(gin.Accounts{ "admin": "password", })) // 受保护的路由 router.GET("/protected", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Access granted"}) }) router.Run(":8080") } ``` 在上述代码中,我们首先创建了一个Gin的路由实例。然后,我们定义了一个验证函数`auth`,该函数根据用户名和密码进行身份验证。 接下来,我们使用`gin.BasicAuth`中间件,并为其提供一个包含预定义用户名和密码的映射。这些用户名和密码将用于验证过程。 然后,我们定义了一个受保护的路由`/protected`,当用户访问该路由时,中间件将自动调用验证函数进行身份验证。如果身份验证成功,将返回一个HTTP 200 OK的响应,消息为"Access granted"。 对于前端应用程序,要发送认证请求,可以使用JavaScript的fetch函数或者Axios库发送HTTP请求,并在请求头中包含基本身份验证信息。 以下是使用fetch函数发送认证请求的示例代码: ```javascript const username = 'admin'; const password = 'password'; const url = 'http://localhost:8080/protected'; const authHeader = 'Basic ' + btoa(username + ':' + password); fetch(url, { headers: { 'Authorization': authHeader } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ``` 在上述示例中,我们首先定义了用户名和密码,并指定要访问的URL。然后,我们创建一个认证头信息,将用户名和密码进行Base64编码,并使用`Basic`前缀拼接。 最后,我们使用fetch函数发送HTTP请求,并在请求头中添加认证头信息。服务器将使用Gin的`BasicAuth`中间件进行身份验证,并根据提供的用户名和密码返回相应的响应。 请注意,上述示例中的代码是使用JavaScript进行发送认证请求的示例。对于其他前端框架或库,例如ReactVue或Angular,也可以使用类似的方式发送认证请求,只需将认证头信息添加到相应的HTTP请求头中即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值