【Golang】如何使用Go Fiber和Gorm ORM构建RESTAPI
Overview
In the past I have written several articles about how we can interact with relational databases, however they were all for the JavaScript and TypeScript community. So this week I will share with you how we can create a simple API and perform a CRUD on a specific table in our database, this time in Go.
In this article, as in other articles I've written in the past in Golang, we'll use the Fiber framework, it's quite simple to use, has a good abstraction layer and contains everything we need to create our API.
【Golang】Golang简介:构建一个迷你Twitter克隆
TABLE OF CONTENTS
TL;DR
This article is for those who want to quickly glance over Golang and build a small project, it serves as an introduction into the language.
After going through the post you will know how to build a simple CRUD app and you will be somehow familiar with Go syntax to start your own project.
If you have feedback you can reach me out on Twitter @tekbog or leave a comment here.
【Go开发】如何使用Go Fiber、Gorm ORM和PostgreSQL构建REST API
【Golang】Go Fiber示例(4):测试应用程序
【Golang】Go Fiber示例(1):Go Fiber Web框架如何发挥作用?
【Golang】Go Fiber示例(2):深入研究内置功能
【Golang】在20分钟内将SAML SSO添加到您的Golang服务中
【Go语言Web开发】使用Golang Keycloak SAML
利用Golang对Keycloak的SAML进行分析。
1.生成证书
SAML的Service Provider需要证书。使用以下命令生成证书:
# openssl req -x509 -newkey rsa:2048 -keyout myservice.key -out myservice.cert -days 365 -nodes -subj "/CN=myservice.example.com"
【Go语言数据库开发】使用 GORM 连接到数据库
GORM正式支持数据库MySQL、PostgreSQL、SQLite、SQL Server
【Go语言数据库开发】Go 中的 Gorm 高级查询
智能选择字段
GORM 允许使用 Select 选择特定字段,如果您经常在应用程序中使用它,也许您想定义一个较小的结构供 API 使用,它可以自动选择特定字段,例如:
type User struct { ID uint Name string Age int Gender string // hundreds of fields } type APIUser struct { ID uint Name string } // Select `id`, `name` automatically when querying db.Model(&User{}).Limit(10).Find(&APIUser{}) // SELECT `id`, `name` FROM `users` LIMIT 10 |
注意 QueryFields 模式将根据当前模型的所有字段名称进行选择