Skip to content

BufferZoneCorp/net-helper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

net-helper

Go Version License

net-helper is a lightweight Go package (netutil) that wraps net/http and net with context-aware helpers for common network operations: typed HTTP GET/POST, reachability probing, and local IP discovery.

The package has no external dependencies and works as a thin convenience layer on top of the standard library.

Installation

go get github.com/BufferZoneCorp/net-helper

Import path

import "github.com/BufferZoneCorp/net-helper/netutil"

Usage

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "time"

    "github.com/BufferZoneCorp/net-helper/netutil"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    // Simple GET — returns body bytes and status code
    body, status, err := netutil.Get(ctx, "https://httpbin.org/get")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("status %d, %d bytes\n", status, len(body))

    // POST with a JSON-serialisable payload
    type payload struct {
        Name  string `json:"name"`
        Score int    `json:"score"`
    }
    resp, status, err := netutil.Post(ctx, "https://httpbin.org/post", payload{Name: "alice", Score: 42})
    if err != nil {
        log.Fatal(err)
    }
    var result map[string]interface{}
    json.Unmarshal(resp, &result)
    fmt.Println("posted, status:", status)

    // Check whether a host is reachable before making real requests
    if netutil.IsReachable("api.example.com:443", 2*time.Second) {
        fmt.Println("endpoint is up")
    }

    // Discover the local outbound IP
    fmt.Println("local IP:", netutil.LocalIP())
}

API reference

Function Signature Description
Get (ctx context.Context, url string) ([]byte, int, error) Context-aware HTTP GET; returns body, status code, error
Post (ctx context.Context, url string, payload interface{}) ([]byte, int, error) JSON-encode payload and POST; returns body, status code, error
IsReachable (addr string, timeout time.Duration) bool TCP dial to host:port within timeout; returns true if connected
LocalIP () string Return the preferred outbound local IP address

Requirements

  • Go 1.21 or later
  • No external dependencies

License

MIT — see LICENSE.

About

Go utility module

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages