golang处理Postman Collection数据的插件库go-postman-collection的使用

Golang处理Postman Collection数据的插件库go-postman-collection的使用

go-postman-collection是一个用于处理Postman Collection的Go模块。它提供了简单的方式来创建、更新和导出Postman Collection格式(v2)的数据,兼容Insomnia。

基本用法

读取Postman Collection

package main

import (
	"os"

	postman "github.com/rbretecher/go-postman-collection"
)

func main() {
	file, err := os.Open("postman_collection.json")
	defer file.Close()

	if err != nil {
		panic(err)
	}

	c, err := postman.ParseCollection(file)

	_ = c
}

创建并保存Postman Collection

package main

import (
	"os"

	postman "github.com/rbretecher/go-postman-collection"
)

func main() {
    c := postman.CreateCollection("My collection", "My awesome collection")

    c.AddItemGroup("A folder").AddItem(&postman.Item{
        Name:    "This is a request",
        Request: Request{
            URL: &URL{
                Raw: "http://www.google.fr",
            },
            Method: postman.Get,
        },
    })

    file, err := os.Create("postman_collection.json")
    defer file.Close()

    if err != nil {
        panic(err)
    }

    err = c.Write(file)

    if err != nil {
        panic(err)
    }
}

Items操作

Items是Postman集合的基本单位,可以是请求(Item)或文件夹(ItemGroup)。

// 创建一个简单的item
item := postman.CreateItem(postman.Item{
    Name:    "A basic request",
    Request: Request{
        URL: &URL{
            Raw: "http://www.google.fr",
        },
        Method: postman.Get,
    }
})

// 创建一个简单的文件夹
folder := postman.CreateItemGroup(postman.ItemGroup{
    Name: "A folder",
})

// 将item添加到文件夹
folder.AddItem(item)

Request操作

作为Item的一部分,Request表示一个HTTP请求。

// 基本请求
req := Request{
    URL: &URL{
        Raw: "http://www.google.fr",
    },
    Method: postman.Get,
}

// 复杂请求
req := postman.Request{
    URL: &postman.URL{
        Raw: "http://www.google.fr",
    },
    Method: postman.Post,
    Body: &postman.Body{
        Mode: "raw",
        Raw:  "{\"key\": \"value\"}",
    },
}

Auth操作

Auth可以添加到RequestItemGroup

// 使用用户名和密码创建基本认证
auth := postman.CreateAuth(postman.Basic, postman.CreateAuthParam("username", "password"))

Variable操作

Variable可以添加到CollectionItemItemGroupURL

v := postman.CreateVariable("env", "prod")

当前支持的功能

目前该库并不支持所有对象。如果你想添加对某个对象的支持,可以提交pull request。

对象 v2.0.0 v2.1.0
Collection
ItemGroup (文件夹)
Item
Request
Response
Event
Variable
Auth

更多关于golang处理Postman Collection数据的插件库go-postman-collection的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang处理Postman Collection数据的插件库go-postman-collection的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用go-postman-collection处理Postman Collection数据

go-postman-collection是一个用于处理Postman Collection数据的Go语言库,它允许开发者以编程方式解析、创建和操作Postman集合。下面我将详细介绍如何使用这个库。

安装

首先安装这个库:

go get github.com/rbretecher/go-postman-collection

基本用法

1. 解析Postman Collection

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"

	postman "github.com/rbretecher/go-postman-collection"
)

func main() {
	// 读取Postman Collection JSON文件
	data, err := ioutil.ReadFile("collection.json")
	if err != nil {
		log.Fatal(err)
	}

	// 解析Collection
	var collection *postman.Collection
	err = json.Unmarshal(data, &collection)
	if err != nil {
		log.Fatal(err)
	}

	// 打印基本信息
	fmt.Printf("Collection名称: %s\n", collection.Info.Name)
	fmt.Printf("描述: %s\n", collection.Info.Description)
	fmt.Printf("包含 %d 个请求\n", len(collection.Items))
}

2. 遍历Collection中的请求

func iterateRequests(collection *postman.Collection) {
	for _, item := range collection.Items {
		// 检查是否是请求项(而不是文件夹)
		if item.Request != nil {
			fmt.Printf("请求名称: %s\n", item.Name)
			fmt.Printf("方法: %s\n", item.Request.Method)
			fmt.Printf("URL: %s\n", item.Request.URL)
			fmt.Println("---")
		} else {
			// 如果是文件夹,递归处理
			fmt.Printf("文件夹: %s\n", item.Name)
			iterateFolder(item)
		}
	}
}

func iterateFolder(item *postman.Items) {
	for _, subItem := range item.Items {
		if subItem.Request != nil {
			fmt.Printf("  |- 请求: %s\n", subItem.Name)
		} else {
			fmt.Printf("  |- 子文件夹: %s\n", subItem.Name)
			iterateFolder(subItem)
		}
	}
}

3. 创建新的Postman Collection

func createNewCollection() *postman.Collection {
	// 创建Collection信息
	info := postman.Info{
		Name:        "示例API集合",
		Description: "这是一个使用go-postman-collection创建的示例集合",
		Schema:      "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
	}

	// 创建Collection
	collection := postman.Collection{
		Info:  info,
		Items: []*postman.Items{},
	}

	// 添加一个请求
	request := postman.Request{
		Method: postman.MethodGet,
		URL:    &postman.URL{Raw: "https://api.example.com/users"},
	}

	requestItem := postman.Items{
		Name:    "获取用户列表",
		Request: &request,
	}

	collection.Items = append(collection.Items, &requestItem)

	return &collection
}

4. 将Collection保存为JSON文件

func saveCollection(collection *postman.Collection, filename string) error {
	data, err := json.MarshalIndent(collection, "", "  ")
	if err != nil {
		return err
	}

	return ioutil.WriteFile(filename, data, 0644)
}

5. 处理请求头和参数

func addHeadersAndParams() *postman.Items {
	// 创建请求
	request := postman.Request{
		Method: postman.MethodPost,
		URL:    &postman.URL{Raw: "https://api.example.com/auth"},
		Header: []*postman.Header{
			{
				Key:   "Content-Type",
				Value: "application/json",
			},
			{
				Key:   "Authorization",
				Value: "Bearer {{token}}",
			},
		},
		Body: &postman.Body{
			Mode: "raw",
			Raw:  `{"username": "user", "password": "pass"}`,
		},
	}

	// 添加URL参数
	request.URL.Query = []*postman.QueryParam{
		{
			Key:   "debug",
			Value: "true",
		},
	}

	return &postman.Items{
		Name:    "认证请求",
		Request: &request,
	}
}

高级用法

1. 处理环境变量

func handleVariables(collection *postman.Collection) {
	// 添加变量
	collection.Variables = []*postman.Variable{
		{
			Key:   "base_url",
			Value: "https://api.example.com",
		},
		{
			Key:   "token",
			Value: "",
		},
	}

	// 在请求中使用变量
	for _, item := range collection.Items {
		if item.Request != nil {
			item.Request.URL.Raw = "{{base_url}}/users"
		}
	}
}

2. 处理认证

func addAuth(request *postman.Request) {
	request.Auth = &postman.Auth{
		Type: "bearer",
		Bearer: []*postman.Bearer{
			{
				Key:   "token",
				Value: "{{token}}",
			},
		},
	}
}

3. 生成cURL命令

func generateCurl(item *postman.Items) (string, error) {
	if item.Request == nil {
		return "", fmt.Errorf("不是有效的请求项")
	}

	curl, err := item.Request.ToCurl()
	if err != nil {
		return "", err
	}

	return curl, nil
}

完整示例

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"

	postman "github.com/rbretecher/go-postman-collection"
)

func main() {
	// 1. 创建新集合
	collection := createNewCollection()
	
	// 2. 添加更多请求
	authItem := addHeadersAndParams()
	collection.Items = append(collection.Items, authItem)
	
	// 3. 处理变量
	handleVariables(collection)
	
	// 4. 保存集合
	err := saveCollection(collection, "my_collection.json")
	if err != nil {
		log.Fatal(err)
	}
	
	// 5. 读取并解析集合
	data, err := ioutil.ReadFile("my_collection.json")
	if err != nil {
		log.Fatal(err)
	}
	
	var parsedCollection *postman.Collection
	err = json.Unmarshal(data, &parsedCollection)
	if err != nil {
		log.Fatal(err)
	}
	
	// 6. 遍历请求
	iterateRequests(parsedCollection)
	
	// 7. 生成cURL命令
	if len(parsedCollection.Items) > 0 {
		curl, err := generateCurl(parsedCollection.Items[0])
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("\ncURL命令:")
		fmt.Println(curl)
	}
}

总结

go-postman-collection库提供了完整的Postman Collection处理能力,包括:

  1. 解析和创建Postman集合
  2. 操作请求、文件夹、变量等元素
  3. 处理认证和请求头
  4. 生成cURL命令
  5. 序列化和反序列化集合数据

这个库特别适合需要以编程方式管理Postman集合的场景,比如自动化测试、API文档生成等。

回到顶部