gitee.com/gricks/utils@v1.0.8/http.go (about)

     1  package utils
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"strings"
     9  
    10  	jsoniter "github.com/json-iterator/go"
    11  )
    12  
    13  // RemoteIP tries to get the remote ip and returns it or ""
    14  func RemoteIP(r *http.Request) string {
    15  	a := r.Header.Get("X-Real-IP")
    16  	if a == "" {
    17  		a = r.Header.Get("X-Forwarded-For")
    18  	}
    19  	if a == "" {
    20  		a = strings.SplitN(r.RemoteAddr, ":", 2)[0]
    21  		if a == "[" {
    22  			a = "127.0.0.1"
    23  		}
    24  	}
    25  	return a
    26  }
    27  
    28  // HTTP json request encode
    29  func MakeHTTPJsonEncodeRequest(url string) func(context.Context, *http.Request, interface{}) error {
    30  	return func(ctx context.Context, r *http.Request, req interface{}) error {
    31  		b := &bytes.Buffer{}
    32  		err := jsoniter.NewEncoder(b).Encode(req)
    33  		if err != nil {
    34  			return err
    35  		}
    36  		r.Body = ioutil.NopCloser(b)
    37  		r.URL.Path = url
    38  		return nil
    39  	}
    40  }
    41  
    42  // HTTP json request decode
    43  func MakeHTTPJsonDecodeRequest(factory func() interface{}) func(ctx context.Context, r *http.Request) (interface{}, error) {
    44  	return func(ctx context.Context, r *http.Request) (interface{}, error) {
    45  		req := factory()
    46  		err := jsoniter.NewDecoder(r.Body).Decode(req)
    47  		return req, err
    48  	}
    49  }
    50  
    51  // HTTP json response encode
    52  func MakeHTTPJsonEncodeResponse() func(context.Context, http.ResponseWriter, interface{}) error {
    53  	return func(ctx context.Context, w http.ResponseWriter, rsp interface{}) error {
    54  		w.Header().Set("Content-Type", "application/json; charset=utf-8")
    55  		return jsoniter.NewEncoder(w).Encode(rsp)
    56  	}
    57  }
    58  
    59  // HTTP json response decode
    60  func MakeHTTPJsonDecodeResponse(factory func() interface{}) func(context.Context, *http.Response) (interface{}, error) {
    61  	return func(ctx context.Context, r *http.Response) (interface{}, error) {
    62  		rsp := factory()
    63  		err := jsoniter.NewDecoder(r.Body).Decode(rsp)
    64  		return rsp, err
    65  	}
    66  }