目录RESTFulGraphQLRESTFulRESTfulAPI简介定义:一种软件架构风格,设计用于利用HTTP协议进行通信。特点:无状态:每次请求包含所有信息。客户端-服务器模式:分离了用户界面与数据管理功能。缓存:提高性能。分层系统:简化架构,支持中间组件。G
定义:一种软件架构风格,设计用于利用HTTP协议进行通信。
特点:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// 发送GET请求
resp, err := http.Get("http://example.com/api/data")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// 读取响应体
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading body:", err)
return
}
// 打印响应内容
fmt.Println(string(body))
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Payload struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
payload := Payload{
Key: "example",
Value: "data",
}
jsonPayload, _ := json.Marshal(payload)
resp, err := http.Post("http://example.com/api/data", "application/json", bytes.NewBuffer(jsonPayload))
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading body:", err)
return
}
fmt.Println(string(body))
}
client := &http.Client{
Timeout: time.Second * 10,
}
req, err := http.NewRequest("GET", "http://example.com/api/data", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
安装go-resty:
go get github.com/go-resty/resty/v2
示例代码:
package main
import (
"github.com/go-resty/resty/v2"
"fmt"
)
func main() {
client := resty.New()
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(map[string]string{"key": "example", "value": "data"}).
Post("http://example.com/api/data")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(resp.String())
}
标准库不支持GraphQL:需要使用第三方库。
常用库:
安装库:
go get github.com/graphql-go/graphql
go get github.com/99designs/gqlgen
package main
import (
"fmt"
"log"
"github.com/99designs/gqlgen/client"
)
type Query struct{}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func (Query) User(id int) (*User, error) {
return &User{ID: id, Name: "Alice"}, nil
}
func main() {
// 创建GraphQL客户端
gqlClient := client.NewHTTPClient("http://localhost:8080/graphql")
// 查询语句
query := `
query GetUser($id: Int!) {
user(id: $id) {
id
name
}
}
`
// 变量
variables := map[string]interface{}{
"id": 1,
}
// 结果类型
var result struct {
User *User `json:"user"`
}
// 发送查询
err := gqlClient.Run(query, variables, &result)
if err != nil {
log.Fatalf("Error running query: %v", err)
}
// 打印结果
fmt.Printf("Result: %+v\n", result)
}
package main
import (
"fmt"
"log"
"github.com/99designs/gqlgen/client"
)
type Query struct{}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Posts []Post `json:"posts"`
}
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
}
func (Query) User(id int) (*User, error) {
user := &User{ID: id, Name: "Alice"}
posts := []Post{{ID: 1, Title: "Post 1"}, {ID: 2, Title: "Post 2"}}
user.Posts = posts
return user, nil
}
func main() {
// 创建GraphQL客户端
gqlClient := client.NewHTTPClient("http://localhost:8080/graphql")
// 查询语句
query := `
query GetUser($id: Int!) {
user(id: $id) {
id
name
posts {
id
title
}
}
}
`
// 变量
variables := map[string]interface{}{
"id": 1,
}
// 结果类型
var result struct {
User *User `json:"user"`
}
// 发送查询
err := gqlClient.Run(query, variables, &result)
if err != nil {
log.Fatalf("Error running query: %v", err)
}
// 打印结果
fmt.Printf("Result: %+v\n", result)
}
package main
import (
"fmt"
"log"
"github.com/99designs/gqlgen/client"
)
type Mutation struct{}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func (Mutation) CreateUser(name string) (*User, error) {
return &User{ID: 1, Name: name}, nil
}
func main() {
// 创建GraphQL客户端
gqlClient := client.NewHTTPClient("http://localhost:8080/graphql")
// 查询语句
mutation := `
mutation CreateUser($name: String!) {
createUser(name: $name) {
id
name
}
}
`
// 变量
variables := map[string]interface{}{
"name": "Bob",
}
// 结果类型
var result struct {
CreateUser *User `json:"createUser"`
}
// 发送查询
err := gqlClient.Run(mutation, variables, &result)
if err != nil {
log.Fatalf("Error running mutation: %v", err)
}
// 打印结果
fmt.Printf("Result: %+v\n", result)
}
package main
import (
"fmt"
"log"
"time"
"github.com/99designs/gqlgen/client"
)
func main() {
// 创建GraphQL客户端
gqlClient := client.NewHTTPClient("http://localhost:8080/graphql")
// 设置超时
gqlClient.Timeout = 10 * time.Second
// 查询语句
query := `
query GetUser($id: Int!) {
user(id: $id) {
id
name
}
}
`
// 变量
variables := map[string]interface{}{
"id": 1,
}
// 结果类型
var result struct {
User *User `json:"user"`
}
// 发送查询
err := gqlClient.Run(query, variables, &result)
if err != nil {
log.Fatalf("Error running query: %v", err)
}
// 打印结果
fmt.Printf("Result: %+v\n", result)
}
安装gql:
go get github.com/graphql-go/graphql
go get github.com/vektah/gqlparser
示例代码:
package main
import (
"fmt"
"log"
"github.com/vektah/gqlparser/v2/parser"
"github.com/vektah/gqlparser/v2/ast"
)
func main() {
// 解析查询
query := `
query GetUser($id: Int!) {
user(id: $id) {
id
name
}
}
`
parsedQuery, err := parser.ParseQuery(query)
if err != nil {
log.Fatalf("Error parsing query: %v", err)
}
// 打印解析结果
fmt.Printf("Parsed Query: %+v\n", parsedQuery)
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!