x

package
v0.0.0-...-5e5f9fa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package http provides a set of functions for working with HTTP requests and responses. It is an extension of the go-zero package https://github.com/zeromicro/go-zero/tree/master/rest/httpx, it provides XML response functions and a base response struct, for example: you can respond an XML string like this:

OkXml(w, "xml string")

then you can receive an XML string like this:

<message><name>anyone</name></message>

besides, it provides a base response struct, as before, you can only respond a json string like this:

httpx.OkJson(w, message{Name: "anyone"})

then you can receive a json string like this:

{"name":"anyone"}

but now, you can respond a json string with base response struct like this:

JsonBaseResponse(w, message{Name: "anyone"})

then you can receive a json string like this:

{"code":0,"msg":"ok","data":{"name":"anyone"}}
Example (JsonBaseResponse)
package main

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"

	xerrors "github.com/zeromicro/x/errors"

	xhttp "github.com/zeromicro/x/http"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type message struct {
	Name string `json:"name" xml:"name"`
}

func main() {
	data := []byte(`{"name":"JsonBaseResponse.example","port":8080}`)
	var serverConf rest.RestConf
	if err := conf.LoadFromJsonBytes(data, &serverConf); err != nil {
		logx.Must(err)
	}

	server, err := rest.NewServer(serverConf)
	if err != nil {
		logx.Must(err)
	}

	server.AddRoutes([]rest.Route{
		{
			Method: http.MethodGet,
			Path:   "/code/msg",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// {"code":1,"msg":"dummy error"}
				xhttp.JsonBaseResponse(writer, xerrors.New(1, "dummy error"))
			},
		},
		{
			Method: http.MethodGet,
			Path:   "/grpc/status",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// {"code":0,"msg":"ok"}
				xhttp.JsonBaseResponse(writer, status.New(codes.OK, "ok"))
			},
		},
		{
			Method: http.MethodGet,
			Path:   "/error",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// {"code":-1,"msg":"dummy error"}
				xhttp.JsonBaseResponse(writer, errors.New("dummy error"))
			},
		},
		{
			Method: http.MethodGet,
			Path:   "/struct",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// {"code":0,"msg":"ok","data":{"name":"anyone"}}
				xhttp.JsonBaseResponse(writer, message{
					Name: "anyone",
				})
			},
		},
	})

	defer server.Stop()
	fmt.Printf("Starting server at %s:%d...\n", serverConf.Host, serverConf.Port)
	server.Start()
}
Output:

Example (XmlBaseResponse)
package main

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"

	xerrors "github.com/zeromicro/x/errors"

	xhttp "github.com/zeromicro/x/http"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type message struct {
	Name string `json:"name" xml:"name"`
}

func main() {
	data := []byte(`{"name":"JsonBaseResponse.example","port":8080}`)
	var serverConf rest.RestConf
	if err := conf.LoadFromJsonBytes(data, &serverConf); err != nil {
		logx.Must(err)
	}

	server, err := rest.NewServer(serverConf)
	if err != nil {
		logx.Must(err)
	}

	server.AddRoutes([]rest.Route{
		{
			Method: http.MethodGet,
			Path:   "/code/msg",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// <xml version="1.0" encoding="UTF-8"><code>1</code><msg>dummy error</msg></xml>
				xhttp.XmlBaseResponse(writer, xerrors.New(1, "dummy error"))
			},
		},
		{
			Method: http.MethodGet,
			Path:   "/grpc/status",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// <xml version="1.0" encoding="UTF-8"><code>0</code><msg>ok</msg></xml>
				xhttp.XmlBaseResponse(writer, status.New(codes.OK, "ok"))
			},
		},
		{
			Method: http.MethodGet,
			Path:   "/error",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// <xml version="1.0" encoding="UTF-8"><code>-1</code><msg>dummy error</msg></xml>
				xhttp.XmlBaseResponse(writer, errors.New("dummy error"))
			},
		},
		{
			Method: http.MethodGet,
			Path:   "/struct",
			Handler: func(writer http.ResponseWriter, request *http.Request) {
				// expected output:
				// <xml version="1.0" encoding="UTF-8"><code>0</code><msg>ok</msg><data><name>anyone</name></data></xml>
				xhttp.XmlBaseResponse(writer, message{Name: "anyone"})
			},
		},
	})

	defer server.Stop()
	fmt.Printf("Starting server at %s:%d...\n", serverConf.Host, serverConf.Port)
	server.Start()
}
Output:

Index

Examples

Constants

View Source
const (

	// BusinessCodeOK represents the business code for success.
	BusinessCodeOK = errcode.CodeOK
	// BusinessMsgOK represents the business message for success.
	BusinessMsgOK = errcode.MsgOK

	// BusinessCodeError represents the business code for error.
	// Any code greater than 0 is a business error.
	BusinessCodeError = 1

	// XmlContentType represents the content type for xml.
	XmlContentType = "application/xml"
)

Variables

This section is empty.

Functions

func FromFile

func FromFile(r *http.Request, name string) (*multipart.FileHeader, error)

FromFile 请求表单文件获取

func GetClientIP

func GetClientIP(r *http.Request) string

GetClientIP 获取客户端的IP

func GetExternalIP

func GetExternalIP() (string, error)

GetExternalIP 通过API获取服务端的外部IP

func GetInternalIP

func GetInternalIP() string

GetInternalIP 获取服务端的内部IP

func GetQuery

func GetQuery(r *http.Request, key string) (string, bool)

GetQuery 返回给定请求查询参数键的字符串值并判断其是否存在

func GetQueryArray

func GetQueryArray(r *http.Request, key string) ([]string, bool)

GetQueryArray 返回给定请求查询参数键的字符串切片值并判断其是否存在

func GetTraceId

func GetTraceId(ctx context.Context) string

GetTraceId 获取链路追踪id

func JsonBaseResponse

func JsonBaseResponse(w http.ResponseWriter, v any)

JsonBaseResponse writes v into w with http.StatusOK.

func JsonBaseResponseCtx

func JsonBaseResponseCtx(ctx context.Context, w http.ResponseWriter, v any)

JsonBaseResponseCtx writes v into w with http.StatusOK.

func OkXml

func OkXml(w http.ResponseWriter, v any)

OkXml writes v into w with 200 OK.

func OkXmlCtx

func OkXmlCtx(ctx context.Context, w http.ResponseWriter, v any)

OkXmlCtx writes v into w with 200 OK.

func Parse

func Parse(r *http.Request, v interface{}) error

Parse 请求体解析

func Query

func Query(r *http.Request, key string) string

Query 返回给定请求查询参数键的字符串值

func QueryArray

func QueryArray(r *http.Request, key string) []string

QueryArray 返回给定请求查询参数键的字符串切片值

func WriteXml

func WriteXml(w http.ResponseWriter, code int, v any)

WriteXml writes v as xml string into w with code.

func WriteXmlCtx

func WriteXmlCtx(ctx context.Context, w http.ResponseWriter, code int, v any)

WriteXmlCtx writes v as xml string into w with code.

func XmlBaseResponse

func XmlBaseResponse(w http.ResponseWriter, v any)

XmlBaseResponse writes v into w with http.StatusOK.

func XmlBaseResponseCtx

func XmlBaseResponseCtx(ctx context.Context, w http.ResponseWriter, v any)

XmlBaseResponseCtx writes v into w with http.StatusOK.

Types

type BaseResponse

type BaseResponse[T any] struct {
	// TraceId represents the request trace id.
	TraceId string `json:"trace_id,omitempty" xml:"trace_id,omitempty" example:"a1b2c3d4e5f6g7h8"` // 链路追踪id
	// Code represents the business code, not the http status code.
	Code int `json:"code" xml:"code" example:"0"`
	// Msg represents the business message, if Code = BusinessCodeOK,
	// and Msg is empty, then the Msg will be set to BusinessMsgOK.
	Msg string `json:"msg" xml:"msg" example:"ok"`
	// Data represents the business data.
	Data T `json:"data,omitempty" xml:"data,omitempty"`

	Count int64 `json:"count,omitempty" xml:"count,omitempty"`
}

BaseResponse is the base response struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL