http

package
v0.0.0-...-8224c48 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: MIT Imports: 8 Imported by: 6

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 = 0
	// BusinessMsgOk represents the business message for success.
	BusinessMsgOk = "ok"

	// BusinessCodeError represents the business code for error.
	BusinessCodeError = -1

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

Variables

This section is empty.

Functions

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 OkHTML

func OkHTML(w http.ResponseWriter, v string)

OkHTML writes v into w with 200 OK.

func OkHTMLCtx

func OkHTMLCtx(ctx context.Context, w http.ResponseWriter, v string)

OkHTMLCtx writes v into w with 200 OK.

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 WriteHTML

func WriteHTML(w http.ResponseWriter, code int, v string)

WriteHTML writes v as HTML string into w with code.

func WriteHTMLCtx

func WriteHTMLCtx(ctx context.Context, w http.ResponseWriter, code int, v string)

WriteHTMLCtx writes v as HTML string into w with code.

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 {
	// Code represents the business code, not the http status code.
	Code int `json:"code" xml:"code"`
	// 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"`
	// Data represents the business data.
	Data T `json:"data,omitempty" xml:"data,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