mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
test&doc: add example and update doc for netutil package
This commit is contained in:
@@ -21,32 +21,32 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
//HttpGet send get http request
|
||||
// HttpGet send get http request.
|
||||
func HttpGet(url string, params ...any) (*http.Response, error) {
|
||||
return doHttpRequest(http.MethodGet, url, params...)
|
||||
}
|
||||
|
||||
//HttpPost send post http request
|
||||
// HttpPost send post http request.
|
||||
func HttpPost(url string, params ...any) (*http.Response, error) {
|
||||
return doHttpRequest(http.MethodPost, url, params...)
|
||||
}
|
||||
|
||||
//HttpPut send put http request
|
||||
// HttpPut send put http request.
|
||||
func HttpPut(url string, params ...any) (*http.Response, error) {
|
||||
return doHttpRequest(http.MethodPut, url, params...)
|
||||
}
|
||||
|
||||
//HttpDelete send delete http request
|
||||
// HttpDelete send delete http request.
|
||||
func HttpDelete(url string, params ...any) (*http.Response, error) {
|
||||
return doHttpRequest(http.MethodDelete, url, params...)
|
||||
}
|
||||
|
||||
// HttpPatch send patch http request
|
||||
// HttpPatch send patch http request.
|
||||
func HttpPatch(url string, params ...any) (*http.Response, error) {
|
||||
return doHttpRequest(http.MethodPatch, url, params...)
|
||||
}
|
||||
|
||||
// ParseHttpResponse decode http response to specified interface
|
||||
// ParseHttpResponse decode http response to specified interface.
|
||||
func ParseHttpResponse(resp *http.Response, obj any) error {
|
||||
if resp == nil {
|
||||
return errors.New("InvalidResp")
|
||||
@@ -55,7 +55,8 @@ func ParseHttpResponse(resp *http.Response, obj any) error {
|
||||
return json.NewDecoder(resp.Body).Decode(obj)
|
||||
}
|
||||
|
||||
// ConvertMapToQueryString convert map to sorted url query string
|
||||
// ConvertMapToQueryString convert map to sorted url query string.
|
||||
// Play: https://go.dev/play/p/jnNt_qoSnRi
|
||||
func ConvertMapToQueryString(param map[string]any) string {
|
||||
if param == nil {
|
||||
return ""
|
||||
|
||||
@@ -92,7 +92,8 @@ func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient {
|
||||
return client
|
||||
}
|
||||
|
||||
// SendRequest send http request
|
||||
// SendRequest send http request.
|
||||
// Play: https://go.dev/play/p/jUSgynekH7G
|
||||
func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error) {
|
||||
err := validateRequest(request)
|
||||
if err != nil {
|
||||
@@ -128,7 +129,8 @@ func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, err
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// DecodeResponse decode response into target object
|
||||
// DecodeResponse decode response into target object.
|
||||
// Play: https://go.dev/play/p/jUSgynekH7G
|
||||
func (client *HttpClient) DecodeResponse(resp *http.Response, target any) error {
|
||||
if resp == nil {
|
||||
return errors.New("invalid target param")
|
||||
@@ -203,7 +205,8 @@ func validateRequest(req *HttpRequest) error {
|
||||
}
|
||||
|
||||
// StructToUrlValues convert struct to url valuse,
|
||||
// only convert the field which is exported and has `json` tag
|
||||
// only convert the field which is exported and has `json` tag.
|
||||
// Play: https://go.dev/play/p/pFqMkM40w9z
|
||||
func StructToUrlValues(targetStruct any) url.Values {
|
||||
rv := reflect.ValueOf(targetStruct)
|
||||
rt := reflect.TypeOf(targetStruct)
|
||||
|
||||
99
netutil/http_example_test.go
Normal file
99
netutil/http_example_test.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package netutil
|
||||
|
||||
import "fmt"
|
||||
|
||||
func ExampleHttpClient_SendRequest() {
|
||||
request := &HttpRequest{
|
||||
RawURL: "https://jsonplaceholder.typicode.com/todos/1",
|
||||
Method: "GET",
|
||||
}
|
||||
|
||||
httpClient := NewHttpClient()
|
||||
resp, err := httpClient.SendRequest(request)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
return
|
||||
}
|
||||
|
||||
type Todo struct {
|
||||
UserId int `json:"userId"`
|
||||
Id int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Completed bool `json:"completed"`
|
||||
}
|
||||
|
||||
var todo Todo
|
||||
err = httpClient.DecodeResponse(resp, &todo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(todo.Id)
|
||||
|
||||
// Output:
|
||||
// 1
|
||||
}
|
||||
|
||||
func ExampleHttpClient_DecodeResponse() {
|
||||
request := &HttpRequest{
|
||||
RawURL: "https://jsonplaceholder.typicode.com/todos/1",
|
||||
Method: "GET",
|
||||
}
|
||||
|
||||
httpClient := NewHttpClient()
|
||||
resp, err := httpClient.SendRequest(request)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
return
|
||||
}
|
||||
|
||||
type Todo struct {
|
||||
UserId int `json:"userId"`
|
||||
Id int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Completed bool `json:"completed"`
|
||||
}
|
||||
|
||||
var todo Todo
|
||||
err = httpClient.DecodeResponse(resp, &todo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(todo.Id)
|
||||
|
||||
// Output:
|
||||
// 1
|
||||
}
|
||||
|
||||
func ExampleStructToUrlValues() {
|
||||
type TodoQuery struct {
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
todoQuery := TodoQuery{
|
||||
Id: 1,
|
||||
Name: "Test",
|
||||
}
|
||||
todoValues := StructToUrlValues(todoQuery)
|
||||
|
||||
fmt.Println(todoValues.Get("id"))
|
||||
fmt.Println(todoValues.Get("name"))
|
||||
|
||||
// Output:
|
||||
// 1
|
||||
// Test
|
||||
}
|
||||
|
||||
func ExampleConvertMapToQueryString() {
|
||||
var m = map[string]any{
|
||||
"c": 3,
|
||||
"a": 1,
|
||||
"b": 2,
|
||||
}
|
||||
|
||||
qs := ConvertMapToQueryString(m)
|
||||
|
||||
fmt.Println(qs)
|
||||
|
||||
// Output:
|
||||
// a=1&b=2&c=3
|
||||
}
|
||||
@@ -9,7 +9,8 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GetInternalIp return internal ipv4
|
||||
// GetInternalIp return internal ipv4.
|
||||
// Play: https://go.dev/play/p/5mbu-gFp7ei
|
||||
func GetInternalIp() string {
|
||||
addr, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
@@ -26,7 +27,8 @@ func GetInternalIp() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetRequestPublicIp return the requested public ip
|
||||
// GetRequestPublicIp return the requested public ip.
|
||||
// Play: https://go.dev/play/p/kxU-YDc_eBo
|
||||
func GetRequestPublicIp(req *http.Request) string {
|
||||
var ip string
|
||||
for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") {
|
||||
@@ -47,7 +49,8 @@ func GetRequestPublicIp(req *http.Request) string {
|
||||
}
|
||||
|
||||
// GetPublicIpInfo return public ip information
|
||||
// return the PublicIpInfo struct
|
||||
// return the PublicIpInfo struct.
|
||||
// Play: https://go.dev/play/p/YDxIfozsRHR
|
||||
func GetPublicIpInfo() (*PublicIpInfo, error) {
|
||||
resp, err := http.Get("http://ip-api.com/json/")
|
||||
if err != nil {
|
||||
@@ -69,7 +72,8 @@ func GetPublicIpInfo() (*PublicIpInfo, error) {
|
||||
return &ip, nil
|
||||
}
|
||||
|
||||
// GetIps return all ipv4 of system
|
||||
// GetIps return all ipv4 of system.
|
||||
// Play: https://go.dev/play/p/NUFfcEmukx1
|
||||
func GetIps() []string {
|
||||
var ips []string
|
||||
|
||||
@@ -89,7 +93,8 @@ func GetIps() []string {
|
||||
return ips
|
||||
}
|
||||
|
||||
// GetMacAddrs get mac address
|
||||
// GetMacAddrs get mac address.
|
||||
// Play: https://go.dev/play/p/Rq9UUBS_Xp1
|
||||
func GetMacAddrs() []string {
|
||||
var macAddrs []string
|
||||
|
||||
@@ -125,7 +130,8 @@ type PublicIpInfo struct {
|
||||
Ip string `json:"query"`
|
||||
}
|
||||
|
||||
// IsPublicIP verify a ip is public or not
|
||||
// IsPublicIP verify a ip is public or not.
|
||||
// Play: https://go.dev/play/p/nmktSQpJZnn
|
||||
func IsPublicIP(IP net.IP) bool {
|
||||
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
|
||||
return false
|
||||
@@ -145,7 +151,8 @@ func IsPublicIP(IP net.IP) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsInternalIP verify an ip is intranet or not
|
||||
// IsInternalIP verify an ip is intranet or not.
|
||||
// Play: https://go.dev/play/p/sYGhXbgO4Cb
|
||||
func IsInternalIP(IP net.IP) bool {
|
||||
if IP.IsLoopback() {
|
||||
return true
|
||||
@@ -159,7 +166,8 @@ func IsInternalIP(IP net.IP) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// EncodeUrl encode url
|
||||
// EncodeUrl encode url.
|
||||
// Play: https://go.dev/play/p/bsZ6BRC4uKI
|
||||
func EncodeUrl(urlStr string) (string, error) {
|
||||
URL, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
|
||||
91
netutil/net_example_test.go
Normal file
91
netutil/net_example_test.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package netutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ExampleGetInternalIp() {
|
||||
internalIp := GetInternalIp()
|
||||
|
||||
result := IsInternalIP(net.ParseIP(internalIp))
|
||||
fmt.Println(result)
|
||||
|
||||
// Output:
|
||||
// true
|
||||
}
|
||||
|
||||
func ExampleGetPublicIpInfo() {
|
||||
ipInfo, err := GetPublicIpInfo()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
result := IsPublicIP(net.ParseIP(ipInfo.Ip))
|
||||
fmt.Println(result)
|
||||
|
||||
// Output:
|
||||
// true
|
||||
}
|
||||
|
||||
func ExampleGetRequestPublicIp() {
|
||||
ip := "36.112.24.10"
|
||||
|
||||
request := http.Request{
|
||||
Method: "GET",
|
||||
Header: http.Header{
|
||||
"X-Forwarded-For": {ip},
|
||||
},
|
||||
}
|
||||
publicIp := GetRequestPublicIp(&request)
|
||||
|
||||
fmt.Println(publicIp)
|
||||
|
||||
// Output:
|
||||
// 36.112.24.10
|
||||
}
|
||||
|
||||
func ExampleIsInternalIP() {
|
||||
ip1 := IsInternalIP(net.ParseIP("127.0.0.1"))
|
||||
ip2 := IsInternalIP(net.ParseIP("192.168.0.1"))
|
||||
ip3 := IsInternalIP(net.ParseIP("36.112.24.10"))
|
||||
|
||||
fmt.Println(ip1)
|
||||
fmt.Println(ip2)
|
||||
fmt.Println(ip3)
|
||||
|
||||
// Output:
|
||||
// true
|
||||
// true
|
||||
// false
|
||||
}
|
||||
|
||||
func ExampleIsPublicIP() {
|
||||
ip1 := IsPublicIP(net.ParseIP("127.0.0.1"))
|
||||
ip2 := IsPublicIP(net.ParseIP("192.168.0.1"))
|
||||
ip3 := IsPublicIP(net.ParseIP("36.112.24.10"))
|
||||
|
||||
fmt.Println(ip1)
|
||||
fmt.Println(ip2)
|
||||
fmt.Println(ip3)
|
||||
|
||||
// Output:
|
||||
// false
|
||||
// false
|
||||
// true
|
||||
}
|
||||
|
||||
func ExampleEncodeUrl() {
|
||||
urlAddr := "http://www.lancet.com?a=1&b=[2]"
|
||||
|
||||
encodedUrl, err := EncodeUrl(urlAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(encodedUrl)
|
||||
|
||||
// Output:
|
||||
// http://www.lancet.com?a=1&b=%5B2%5D
|
||||
}
|
||||
Reference in New Issue
Block a user