跳转到主要内容

【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 中的 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 模式将根据当前模型的所有字段名称进行选择