跳转到主要内容

【Go】为什么我们更喜欢Go 作为后端

There are tons of backend programming languages out there. They all have their fair share of advantages for different situations. For example Java is great for enterprise backends, Typescript + NodeJS is useful for full stack development. There’s also PHP and Ruby, which… I don’t know why you’d choose those, but to each their own I guess.

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

【Go语言Web开发】Go 代码示例:json.Encoder 和 json.Decoder

这些是为客户端和服务器端编码/解码 json 的代码示例。

让我们从服务器端开始。

解码请求


定义请求参数:首先,定义表示请求参数的结构。

type UserRequest struct {
        Name  string `json:"name"`
        Email string `json:"email"`
}


json.Decoder:在请求处理程序中,用请求体创建一个解码器,并用结构体的指针调用解码方法。

【Go语言Web开发】使用 Go 的 net/http 包对 JSON 进行编码和解码

这是一个非常常见的任务:编码 JSON 并将其发送到服务器,在服务器上解码 JSON,反之亦然。令人惊讶的是,关于如何做到这一点的现有资源并不是很清楚。因此,让我们来看看每个案例,对于以下简单的 User 对象:

type User struct{
    Id      string
    Balance uint64
}


在 POST/PUT 请求的正文中发送 JSON


让我们从最棘手的开始:Go 的 http.Request 的主体是一个 io.Reader,如果你有一个结构,它就不太适合 - 你需要先编写结构,然后将其复制到阅读器。

【Go语言中级开发】结构到 JSON 的 Golang 数组

下面的代码是将结构数组转换为 JSON 的示例。

package main

import (
"log"
"encoding/json"
)

type Fruit struct {
Name string `json:"name"`
Quantity int `json:"quantity"`
}

func main() {
a := Fruit{Name:"Apple",Quantity:1}
o := Fruit{Name:"Orange",Quantity:2}

var fs []Fruit
fs = append(fs, a)
fs = append(fs, o)
log.Println(fs)

j, _ := json.Marshal(fs)
log.Println(string(j))

j, _ = json.MarshalIndent(fs, "", " ")
log.Println(string(j))
}

 

运行它将产生如下输出。

【Go语言中级开发】Golang 中 JSON 的完整指南(附示例)

在这篇文章中,我们将学习如何以最简单的方式在 Go 中使用 JSON。

我们将学习如何将 JSON 原始数据(字符串或字节)转换为 Go 类型,如结构、数组和切片,以及非结构化数据,如映射和空接口。

banner

JSON 被用作数据序列化的事实标准,在本文结束时,您将熟悉如何在 Go Unmarshaling Raw JSON Data 中对 JSON 进行编组(编码)和解组(解码)

Unmarshaling Raw JSON Data


Go 的 JSON 标准库提供的 Unmarshal 函数可以让我们以 []byte 变量的形式解析原始 JSON 数据。

我们可以将 JSON 字符串转换为字节,并将数据解组为变量地址:

【Go语言中级开发】在 Go 中编写 JSON REST API 的技巧

本文提供了有关使用普通 Go HTTP 处理程序编写 JSON REST API 的随机提示。

  • 使用匿名类型解析 JSON
  • 使用 http.MaxBytesReader 限制请求长度
  • 使用 map[string]interface{} 生成 JSON
  • 使用 MarshalJSON 自定义 JSON 输出
  • 使用中间件处理错误
  • 使用结构对处理程序进行分组
  • 使用分段/编码

使用匿名类型解析 JSON


而不是声明全局类型: