1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-13 17:22:27 +08:00

test&doc: add example and update doc for netutil package

This commit is contained in:
dudaodong
2023-01-08 16:54:29 +08:00
parent da2eb66657
commit b05a0a91c3
7 changed files with 334 additions and 67 deletions

View File

@@ -162,7 +162,7 @@ import "github.com/duke-git/lancet/v2/condition"
[[play](https://go.dev/play/p/W1SSUmt6pvr)] [[play](https://go.dev/play/p/W1SSUmt6pvr)]
- **<big>Or</big>** : returns false if neither a nor b is truthy. - **<big>Or</big>** : returns false if neither a nor b is truthy.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Or)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Or)]
[[play](https://go.dev/play/p/UlQTxHaeEkq)]] [[play](https://go.dev/play/p/UlQTxHaeEkq)]]
- **<big>Xor</big>** : returns true if a or b but not both is truthy. - **<big>Xor</big>** : returns true if a or b but not both is truthy.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Xor)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Xor)]
[[play](https://go.dev/play/p/gObZrW7ZbG8)] [[play](https://go.dev/play/p/gObZrW7ZbG8)]
@@ -340,8 +340,6 @@ import "github.com/duke-git/lancet/v2/cryptor"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/cryptor.md#RsaDecrypt)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/cryptor.md#RsaDecrypt)]
[[play](https://go.dev/play/p/uef0q1fz53I)] [[play](https://go.dev/play/p/uef0q1fz53I)]
### 6. Datetime package supports date and time format and compare. ### 6. Datetime package supports date and time format and compare.
```go ```go
@@ -413,8 +411,6 @@ import hashmap "github.com/duke-git/lancet/v2/datastructure/hashmap"
- **<big>Hashmap</big>** : hash map structure. - **<big>Hashmap</big>** : hash map structure.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datastructure/hashmap.md)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/datastructure/hashmap.md)]
### 8. Fileutil package implements some basic functions for file operations. ### 8. Fileutil package implements some basic functions for file operations.
```go ```go
@@ -514,8 +510,6 @@ import "github.com/duke-git/lancet/v2/function"
- **<big>Watcher</big>** : Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution. - **<big>Watcher</big>** : Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Watcher)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Watcher)]
### 11. Maputil package includes some functions to manipulate map. ### 11. Maputil package includes some functions to manipulate map.
```go ```go
@@ -601,26 +595,62 @@ import "github.com/duke-git/lancet/v2/netutil"
#### Function list: #### Function list:
- [ConvertMapToQueryString](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#ConvertMapToQueryString) - **<big>ConvertMapToQueryString</big>** : convert map to sorted url query string.
- [EncodeUrl](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#EncodeUrl) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#ConvertMapToQueryString)]
- [GetInternalIp](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetInternalIp) [[play](https://go.dev/play/p/jnNt_qoSnRi)]
- [GetIps](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetIps) - **<big>EncodeUrl</big>** : encode url(?a=1&b=[2] -> ?a=1&b=%5B2%5D).
- [GetMacAddrs](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetMacAddrs) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#EncodeUrl)]
- [GetPublicIpInfo](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetPublicIpInfo) [[play](https://go.dev/play/p/bsZ6BRC4uKI)]
- [GetRequestPublicIp](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetRequestPublicIp) - **<big>GetInternalIp</big>** : return internal ipv4.
- [IsPublicIP](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#IsPublicIP) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetInternalIp)]
- [IsInternalIP](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#IsInternalIP) [[play](https://go.dev/play/p/5mbu-gFp7ei)]
- [HttpRequest](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpRequest) - **<big>GetIps</big>** : return all ipv4 of current system.
- [HttpClient](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpClient) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetIps)]
- [SendRequest](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#SendRequest) [[play](https://go.dev/play/p/NUFfcEmukx1)]
- [DecodeResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#DecodeResponse) - **<big>GetMacAddrs</big>** : return mac address of current system.
- [StructToUrlValues](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#StructToUrlValues) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetMacAddrs)]
- [HttpGet<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpGet) [[play](https://go.dev/play/p/Rq9UUBS_Xp1)]
- [HttpDelete<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpDelete) - **<big>GetPublicIpInfo</big>** : return [public ip information](http://ip-api.com/json/).
- [HttpPost<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPost) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetPublicIpInfo)]
- [HttpPut<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPut) [[play](https://go.dev/play/p/YDxIfozsRHR)]
- [HttpPatch<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPatch) - **<big>GetRequestPublicIp</big>** : return the http request public ip.
- [ParseHttpResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#ParseHttpResponse) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetRequestPublicIp)]
[[play](https://go.dev/play/p/kxU-YDc_eBo)]
- **<big>IsPublicIP</big>** : verify a ip is public or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#IsPublicIP)]
[[play](https://go.dev/play/p/nmktSQpJZnn)]
- **<big>IsInternalIP</big>** : verify an ip is intranet or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#IsInternalIP)]
[[play](https://go.dev/play/p/sYGhXbgO4Cb)]
- **<big>HttpRequest</big>** : a composed http request used for HttpClient send request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpRequest)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>HttpClient</big>** : a http client tool, used for sending http request
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpClient)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>SendRequest</big>** : send http request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#SendRequest)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>DecodeResponse</big>** : decode http response into target object.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#DecodeResponse)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>StructToUrlValues</big>** : convert struct to url valuse.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#StructToUrlValues)]
[[play](https://go.dev/play/p/pFqMkM40w9z)]
- **<big>HttpGet<sup>deprecated</sup></big>** : send get http request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpGet)]
- **<big>HttpDelete<sup>deprecated</sup></big>** : send delete http request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpDelete)]
- **<big>HttpPost<sup>deprecated</sup></big>** : send post http request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPost)]
- **<big>HttpPut<sup>deprecated</sup></big>** : send put http request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPut)]
- **<big>HttpPatch<sup>deprecated</sup></big>** : send patch http request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPatch)]
- **<big>ParseHttpResponse</big>** : decode http response into target object.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#ParseHttpResponse)]
### 14. Random package implements some basic functions to generate random int and string. ### 14. Random package implements some basic functions to generate random int and string.
@@ -679,8 +709,6 @@ import "github.com/duke-git/lancet/v2/retry"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/retry.md#RetryTimes)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/retry.md#RetryTimes)]
[[play](https://go.dev/play/p/ssfVeU2SwLO)] [[play](https://go.dev/play/p/ssfVeU2SwLO)]
### 16. Slice contains some functions to manipulate slice. ### 16. Slice contains some functions to manipulate slice.
```go ```go

View File

@@ -600,26 +600,63 @@ import "github.com/duke-git/lancet/v2/netutil"
#### 函数列表: #### 函数列表:
- [ConvertMapToQueryString](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#ConvertMapToQueryString) - **<big>ConvertMapToQueryString</big>** : 将map转换成http查询字符串。
- [GetInternalIp](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetInternalIp) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#ConvertMapToQueryString)]
- [EncodeUrl](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#EncodeUrl) [[play](https://go.dev/play/p/jnNt_qoSnRi)]
- [GetIps](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetIps) - **<big>EncodeUrl</big>** : 编码url query string的值(?a=1&b=[2] -> ?a=1&b=%5B2%5D)。
- [GetMacAddrs](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#GetMacAddrs) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#EncodeUrl)]
- [GetPublicIpInfo](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetPublicIpInfo) [[play](https://go.dev/play/p/bsZ6BRC4uKI)]
- [GetRequestPublicIp](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetRequestPublicIp) - **<big>GetInternalIp</big>** : 获取内部ipv4。
- [IsPublicIP](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#IsPublicIP) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetInternalIp)]
- [IsInternalIP](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#IsInternalIP) [[play](https://go.dev/play/p/5mbu-gFp7ei)]
- [HttpRequest](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpRequest) - **<big>GetIps</big>** : 获取系统ipv4地址列表。
- [HttpClient](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpClient) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetIps)]
- [SendRequest](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#SendRequest) [[play](https://go.dev/play/p/NUFfcEmukx1)]
- [DecodeResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#DecodeResponse) - **<big>GetMacAddrs</big>** : 获取系统mac地址列。
- [StructToUrlValues](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#StructToUrlValues) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetMacAddrs)]
- [HttpGet<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpGet) [[play](https://go.dev/play/p/Rq9UUBS_Xp1)]
- [HttpDelete<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpDelete) - **<big>GetPublicIpInfo</big>** : 获取[公网ip信息](http://ip-api.com/json/).
- [HttpPost<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPost) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetPublicIpInfo)]
- [HttpPut<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPut) [[play](https://go.dev/play/p/YDxIfozsRHR)]
- [HttpPatch<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPatch) - **<big>GetRequestPublicIp</big>** : 获取http请求ip。
- [ParseHttpResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#ParseHttpResponse) [[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#GetRequestPublicIp)]
[[play](https://go.dev/play/p/kxU-YDc_eBo)]
- **<big>IsPublicIP</big>** : 判断ip是否是公共ip。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#IsPublicIP)]
[[play](https://go.dev/play/p/nmktSQpJZnn)]
- **<big>IsInternalIP</big>** : 判断ip是否是局域网ip。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#IsInternalIP)]
[[play](https://go.dev/play/p/sYGhXbgO4Cb)]
- **<big>HttpRequest</big>** : 用于抽象HTTP请求实体的结构。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpRequest)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>HttpClient</big>** : 用于发送HTTP请求。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpClient)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>SendRequest</big>** : 发送http请求。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#SendRequest)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>DecodeResponse</big>** : 解析http响应体到目标结构体。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#DecodeResponse)]
[[play](https://go.dev/play/p/jUSgynekH7G)]
- **<big>StructToUrlValues</big>** : 将结构体转为url values, 仅转化结构体导出字段并且包含`json` tag。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#StructToUrlValues)]
[[play](https://go.dev/play/p/pFqMkM40w9z)]
- **<big>HttpGet<sup>deprecated</sup></big>** : 发送http get请求已弃用SendRequest代替
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpGet)]
- **<big>HttpDelete<sup>deprecated</sup></big>** : 发送http delete请求已弃用SendRequest代替
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpDelete)]
- **<big>HttpPost<sup>deprecated</sup></big>** : 发送http post请求已弃用SendRequest代替
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPost)]
- **<big>HttpPut<sup>deprecated</sup></big>** : 发送http put请求已弃用SendRequest代替
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPut)]
- **<big>HttpPatch<sup>deprecated</sup></big>** : 发送http patch请求已弃用SendRequest代替
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPatch)]
- **<big>ParseHttpResponse</big>** : 解析http响应体到目标结构体。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#ParseHttpResponse)]
### 14. random 随机数生成器包,可以生成随机[]bytes, int, string。 ### 14. random 随机数生成器包,可以生成随机[]bytes, int, string。

View File

@@ -21,32 +21,32 @@ import (
"strings" "strings"
) )
//HttpGet send get http request // HttpGet send get http request.
func HttpGet(url string, params ...any) (*http.Response, error) { func HttpGet(url string, params ...any) (*http.Response, error) {
return doHttpRequest(http.MethodGet, url, params...) 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) { func HttpPost(url string, params ...any) (*http.Response, error) {
return doHttpRequest(http.MethodPost, url, params...) 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) { func HttpPut(url string, params ...any) (*http.Response, error) {
return doHttpRequest(http.MethodPut, url, params...) 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) { func HttpDelete(url string, params ...any) (*http.Response, error) {
return doHttpRequest(http.MethodDelete, url, params...) 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) { func HttpPatch(url string, params ...any) (*http.Response, error) {
return doHttpRequest(http.MethodPatch, url, params...) 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 { func ParseHttpResponse(resp *http.Response, obj any) error {
if resp == nil { if resp == nil {
return errors.New("InvalidResp") return errors.New("InvalidResp")
@@ -55,7 +55,8 @@ func ParseHttpResponse(resp *http.Response, obj any) error {
return json.NewDecoder(resp.Body).Decode(obj) 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 { func ConvertMapToQueryString(param map[string]any) string {
if param == nil { if param == nil {
return "" return ""

View File

@@ -92,7 +92,8 @@ func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient {
return client 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) { func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error) {
err := validateRequest(request) err := validateRequest(request)
if err != nil { if err != nil {
@@ -128,7 +129,8 @@ func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, err
return resp, nil 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 { func (client *HttpClient) DecodeResponse(resp *http.Response, target any) error {
if resp == nil { if resp == nil {
return errors.New("invalid target param") return errors.New("invalid target param")
@@ -203,7 +205,8 @@ func validateRequest(req *HttpRequest) error {
} }
// StructToUrlValues convert struct to url valuse, // 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 { func StructToUrlValues(targetStruct any) url.Values {
rv := reflect.ValueOf(targetStruct) rv := reflect.ValueOf(targetStruct)
rt := reflect.TypeOf(targetStruct) rt := reflect.TypeOf(targetStruct)

View 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
}

View File

@@ -9,7 +9,8 @@ import (
"strings" "strings"
) )
// GetInternalIp return internal ipv4 // GetInternalIp return internal ipv4.
// Play: https://go.dev/play/p/5mbu-gFp7ei
func GetInternalIp() string { func GetInternalIp() string {
addr, err := net.InterfaceAddrs() addr, err := net.InterfaceAddrs()
if err != nil { if err != nil {
@@ -26,7 +27,8 @@ func GetInternalIp() string {
return "" 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 { func GetRequestPublicIp(req *http.Request) string {
var ip string var ip string
for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") { 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 // GetPublicIpInfo return public ip information
// return the PublicIpInfo struct // return the PublicIpInfo struct.
// Play: https://go.dev/play/p/YDxIfozsRHR
func GetPublicIpInfo() (*PublicIpInfo, error) { func GetPublicIpInfo() (*PublicIpInfo, error) {
resp, err := http.Get("http://ip-api.com/json/") resp, err := http.Get("http://ip-api.com/json/")
if err != nil { if err != nil {
@@ -69,7 +72,8 @@ func GetPublicIpInfo() (*PublicIpInfo, error) {
return &ip, nil 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 { func GetIps() []string {
var ips []string var ips []string
@@ -89,7 +93,8 @@ func GetIps() []string {
return ips return ips
} }
// GetMacAddrs get mac address // GetMacAddrs get mac address.
// Play: https://go.dev/play/p/Rq9UUBS_Xp1
func GetMacAddrs() []string { func GetMacAddrs() []string {
var macAddrs []string var macAddrs []string
@@ -125,7 +130,8 @@ type PublicIpInfo struct {
Ip string `json:"query"` 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 { func IsPublicIP(IP net.IP) bool {
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() { if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
return false return false
@@ -145,7 +151,8 @@ func IsPublicIP(IP net.IP) bool {
return false 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 { func IsInternalIP(IP net.IP) bool {
if IP.IsLoopback() { if IP.IsLoopback() {
return true return true
@@ -159,7 +166,8 @@ func IsInternalIP(IP net.IP) bool {
return false return false
} }
// EncodeUrl encode url // EncodeUrl encode url.
// Play: https://go.dev/play/p/bsZ6BRC4uKI
func EncodeUrl(urlStr string) (string, error) { func EncodeUrl(urlStr string) (string, error) {
URL, err := url.Parse(urlStr) URL, err := url.Parse(urlStr)
if err != nil { if err != nil {

View 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
}