netutil

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2024 License: MIT Imports: 21 Imported by: 29

Documentation

Overview

Package netutil implements some basic functions to send http request and get ip info. Note: HttpGet, HttpPost, HttpDelete, HttpPut, HttpPatch, function param `url` is required. HttpGet, HttpPost, HttpDelete, HttpPut, HttpPatch, function param `params` is variable, the order is: params[0] is header which type should be http.Header or map[string]string, params[1] is query string param which type should be url.Values or map[string]string, when content-type header is multipart/form-data or application/x-www-form-urlencoded params[2] is post body which type should be []byte. params[3] is http client which type should be http.Client.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertMapToQueryString

func ConvertMapToQueryString(param map[string]any) string

ConvertMapToQueryString convert map to sorted url query string. Play: https://go.dev/play/p/jnNt_qoSnRi

Example
var m = map[string]any{
	"c": 3,
	"a": 1,
	"b": 2,
}

qs := ConvertMapToQueryString(m)

fmt.Println(qs)
Output:

a=1&b=2&c=3

func DownloadFile added in v2.1.20

func DownloadFile(filepath string, url string) error

DownloadFile will download the file exist in url to a local file.

func EncodeUrl added in v2.1.3

func EncodeUrl(urlStr string) (string, error)

EncodeUrl encode url. Play: https://go.dev/play/p/bsZ6BRC4uKI

Example
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

func GetInternalIp

func GetInternalIp() string

GetInternalIp return internal ipv4. Play: https://go.dev/play/p/5mbu-gFp7ei

Example
internalIp := GetInternalIp()

result := IsInternalIP(net.ParseIP(internalIp))
fmt.Println(result)
Output:

true

func GetIps

func GetIps() []string

GetIps return all ipv4 of system. Play: https://go.dev/play/p/NUFfcEmukx1

func GetMacAddrs

func GetMacAddrs() []string

GetMacAddrs get mac address. Play: https://go.dev/play/p/Rq9UUBS_Xp1

func GetRequestPublicIp added in v2.1.2

func GetRequestPublicIp(req *http.Request) string

GetRequestPublicIp return the requested public ip. Play: https://go.dev/play/p/kxU-YDc_eBo

Example
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 HttpDelete

func HttpDelete(url string, params ...any) (*http.Response, error)

HttpDelete send delete http request.

func HttpGet

func HttpGet(url string, params ...any) (*http.Response, error)

HttpGet send get http request.

func HttpPatch

func HttpPatch(url string, params ...any) (*http.Response, error)

HttpPatch send patch http request.

func HttpPost

func HttpPost(url string, params ...any) (*http.Response, error)

HttpPost send post http request.

func HttpPut

func HttpPut(url string, params ...any) (*http.Response, error)

HttpPut send put http request.

func IsInternalIP added in v2.1.2

func IsInternalIP(IP net.IP) bool

IsInternalIP verify an ip is intranet or not. Play: https://go.dev/play/p/sYGhXbgO4Cb

Example
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 IsPingConnected added in v2.1.20

func IsPingConnected(host string) bool

IsPingConnected checks if can ping specified host or not. Play: https://go.dev/play/p/q8OzTijsA87

Example
// result1 := IsPingConnected("bing.com")
result2 := IsPingConnected("www.!@#&&&.com")

// fmt.Println(result1)
fmt.Println(result2)
Output:

false

func IsPublicIP

func IsPublicIP(IP net.IP) bool

IsPublicIP verify a ip is public or not. Play: https://go.dev/play/p/nmktSQpJZnn

Example
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 IsTelnetConnected added in v2.1.20

func IsTelnetConnected(host string, port string) bool

IsTelnetConnected checks if can telnet specified host or not. Play: https://go.dev/play/p/yiLCGtQv_ZG

Example
result1 := IsTelnetConnected("bing.com", "80")
result2 := IsTelnetConnected("www.baidu.com", "123")

fmt.Println(result1)
fmt.Println(result2)
Output:

true
false

func ParseHttpResponse

func ParseHttpResponse(resp *http.Response, obj any) error

ParseHttpResponse decode http response to specified interface.

func StructToUrlValues added in v2.1.6

func StructToUrlValues(targetStruct any) (url.Values, error)

StructToUrlValues convert struct to url valuse, only convert the field which is exported and has `json` tag. Play: https://go.dev/play/p/pFqMkM40w9z

Example
type TodoQuery struct {
	Id     int    `json:"id"`
	UserId int    `json:"userId"`
	Name   string `json:"name,omitempty"`
	Status string
}
item1 := TodoQuery{
	Id:     1,
	UserId: 123,
	Name:   "test",
	Status: "completed",
}
queryValues1, err := StructToUrlValues(item1)
if err != nil {
	return
}

item2 := TodoQuery{
	Id:     2,
	UserId: 456,
}
queryValues2, _ := StructToUrlValues(item2)

fmt.Println(queryValues1.Get("id"))
fmt.Println(queryValues1.Get("userId"))
fmt.Println(queryValues1.Get("name"))
fmt.Println(queryValues1.Get("status"))

fmt.Println(queryValues2.Get("id"))
fmt.Println(queryValues2.Get("userId"))
fmt.Println(queryValues2.Get("name"))
Output:

1
123
test

2
456

func UploadFile added in v2.1.20

func UploadFile(filepath string, server string) (bool, error)

DownloadFile will upload the file to a server.

Types

type File added in v2.2.2

type File struct {
	Content   []byte
	Path      string
	FieldName string
	FileName  string
}

File struct is a combination of file attributes

type HttpClient added in v2.1.6

type HttpClient struct {
	*http.Client
	TLS     *tls.Config
	Request *http.Request
	Config  HttpClientConfig
	Context context.Context
}

HttpClient is used for sending http request.

func NewHttpClient added in v2.1.6

func NewHttpClient() *HttpClient

NewHttpClient make a HttpClient instance.

func NewHttpClientWithConfig added in v2.1.6

func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient

NewHttpClientWithConfig make a HttpClient instance with pass config.

func (*HttpClient) DecodeResponse added in v2.1.6

func (client *HttpClient) DecodeResponse(resp *http.Response, target any) error

DecodeResponse decode response into target object. Play: https://go.dev/play/p/jUSgynekH7G

Example
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 (*HttpClient) SendRequest added in v2.1.6

func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error)

SendRequest send http request. Play: https://go.dev/play/p/jUSgynekH7G

type HttpClientConfig added in v2.1.6

type HttpClientConfig struct {
	SSLEnabled       bool
	TLSConfig        *tls.Config
	Compressed       bool
	HandshakeTimeout time.Duration
	ResponseTimeout  time.Duration
	Verbose          bool
}

HttpClientConfig contains some configurations for http client

type HttpRequest added in v2.1.6

type HttpRequest struct {
	RawURL      string
	Method      string
	Headers     http.Header
	QueryParams url.Values
	FormData    url.Values
	File        *File
	Body        []byte
}

HttpRequest struct is a composed http request

type PublicIpInfo

type PublicIpInfo struct {
	Status      string  `json:"status"`
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	Region      string  `json:"region"`
	RegionName  string  `json:"regionName"`
	City        string  `json:"city"`
	Lat         float64 `json:"lat"`
	Lon         float64 `json:"lon"`
	Isp         string  `json:"isp"`
	Org         string  `json:"org"`
	As          string  `json:"as"`
	Ip          string  `json:"query"`
}

PublicIpInfo public ip info: country, region, isp, city, lat, lon, ip

func GetPublicIpInfo

func GetPublicIpInfo() (*PublicIpInfo, error)

GetPublicIpInfo return public ip information return the PublicIpInfo struct. Play: https://go.dev/play/p/YDxIfozsRHR

type SetFileFunc added in v2.2.2

type SetFileFunc func(req *http.Request, values url.Values) error

Jump to

Keyboard shortcuts

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