CreateWorld.go 2.01 KB
Newer Older
Ford committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// WorldCreateRequest 定义了创建世界时发送的请求体的结构体
type WorldCreateRequest struct {
	Auth     string `json:"auth"`
	Name     string `json:"name"`
	BgInfo   string `json:"BgInfo,omitempty"`
	UserInfo string `json:"userInfo"`
}

// WorldCreateResponse 定义了创建世界时接受的响应体的结构体
type WorldCreateResponse struct {
	Code    int    `json:"code"`
	ISLIUid string `json:"ISLIUid"`
	WObj    string `json:"WObj"`
	ISLIU   string `json:"ISLIU"`
}

// CreateWorld 是向指定的地址发送创建世界请求的函数
func CreateWorld(url string, request WorldCreateRequest) (*WorldCreateResponse, error) {
	// 将请求体编码为 JSON
	requestBody, err := json.Marshal(request)
	if err != nil {
		return nil, fmt.Errorf("failed to encode request body: %w", err)
	}

	// 创建 POST 请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %w", err)
	}
	defer resp.Body.Close()

	// 读取和解码响应体
	var response WorldCreateResponse
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %w", err)
	}

	err = json.Unmarshal(respBody, &response)
	if err != nil {
		return nil, fmt.Errorf("failed to decode response body: %w", err)
	}

	return &response, nil
}

func main() {
	// 示例请求数据
	requestData := WorldCreateRequest{
		Auth:     "your_auth_signature",
		Name:     "情圣日记",
		BgInfo:   "我是罗翔爱徒",
		UserInfo: `{"name":"张三","bk":"罗翔爱徒"}`,
	}

	// 发送请求并接收响应
	response, err := CreateWorld("http://52.83.116.11:13679/world/new", requestData)
	if err != nil {
		fmt.Println("Error creating world:", err)
		return
	}

	// 打印响应结果
	fmt.Println("Response Code:", response.Code)
	fmt.Println("ISLIUid:", response.ISLIUid)
	fmt.Println("WObj:", response.WObj)
	fmt.Println("ISLIU:", response.ISLIU)
}