httputil

package
v0.0.0-...-14a125a Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 19 Imported by: 0

README

httputil Package

Extremely simple HTTP client utilities that reduce 30+ lines to 2-3 lines.

극도로 간단한 HTTP 클라이언트 유틸리티로 30줄 이상의 코드를 2-3줄로 줄입니다.

Version / 버전: v1.10.004 Package Path / 패키지 경로: github.com/arkd0ng/go-utils/httputil


Table of Contents / 목차


Features / 주요 기능

Extreme Simplicity / 극도의 간결함
  • 30+ lines → 2-3 lines of code reduction
  • 30줄 이상 → 2-3줄로 코드 감소
  • Zero boilerplate for common HTTP operations
  • 일반적인 HTTP 작업에 보일러플레이트 코드 불필요
Core Features / 핵심 기능

RESTful HTTP Methods / RESTful HTTP 메서드

  • GET, POST, PUT, PATCH, DELETE
  • Context variants for all methods (cancellation & timeout support)
  • 모든 메서드의 Context 버전 (취소 및 타임아웃 지원)

Automatic JSON Handling / 자동 JSON 처리

  • Automatic request body encoding
  • Automatic response body decoding
  • 요청 본문 자동 인코딩
  • 응답 본문 자동 디코딩

Smart Retry Logic / 스마트 재시도 로직

  • Configurable retry attempts (default: 3)
  • Exponential backoff with jitter
  • Automatic retry on network errors and 5xx responses
  • 설정 가능한 재시도 횟수 (기본값: 3)
  • 지터가 있는 지수 백오프
  • 네트워크 오류 및 5xx 응답 시 자동 재시도

Response Helpers / 응답 헬퍼

  • Rich Response wrapper with 20+ helper methods
  • Status code checks (IsSuccess, IsOK, IsNotFound, etc.)
  • Body access (Body(), String(), JSON())
  • 20개 이상의 헬퍼 메서드를 가진 풍부한 Response 래퍼
  • 상태 코드 확인 (IsSuccess, IsOK, IsNotFound 등)
  • 본문 접근 (Body(), String(), JSON())

File Operations / 파일 작업

  • File download with progress tracking
  • File upload with multipart form data
  • Progress callbacks for large files
  • 진행 상황 추적과 함께 파일 다운로드
  • multipart form data를 사용한 파일 업로드
  • 대용량 파일을 위한 진행 상황 콜백

URL & Form Builders / URL 및 Form 빌더

  • Fluent API for building URLs and forms
  • Conditional parameters (ParamIf, AddIf)
  • URL utilities (JoinURL, AddQueryParams, GetDomain, etc.)
  • URL 및 폼 구축을 위한 Fluent API
  • 조건부 매개변수 (ParamIf, AddIf)
  • URL 유틸리티 (JoinURL, AddQueryParams, GetDomain 등)

Rich Configuration / 풍부한 설정

  • Functional options pattern for flexible configuration
  • 12 built-in options (timeout, headers, auth, retry, etc.)
  • 함수형 옵션 패턴으로 유연한 설정
  • 12개 내장 옵션 (타임아웃, 헤더, 인증, 재시도 등)

Rich Error Types / 풍부한 에러 타입

  • HTTPError (status code, body, URL)
  • RetryError (failed attempts tracking)
  • TimeoutError (timeout detection)
  • HTTPError (상태 코드, 본문, URL)
  • RetryError (실패한 시도 추적)
  • TimeoutError (타임아웃 감지)

Zero External Dependencies / 제로 외부 의존성

  • Standard library only (net/http, encoding/json, mime/multipart)
  • 표준 라이브러리만 사용 (net/http, encoding/json, mime/multipart)

Installation / 설치

Prerequisites / 전제 조건
  • Go 1.18 or later (for generics support)
  • Go 1.18 이상 (제네릭 지원)
Install Package / 패키지 설치
go get github.com/arkd0ng/go-utils/httputil
Import / 임포트
import "github.com/arkd0ng/go-utils/httputil"

Quick Start / 빠른 시작

1. Simple GET Request / 간단한 GET 요청

Before (30+ lines):

// Traditional approach / 전통적인 방식
client := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest("GET", "https://api.example.com/users", nil)
if err != nil {
    log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer token123")
req.Header.Set("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode != 200 {
    body, _ := io.ReadAll(resp.Body)
    log.Fatalf("HTTP %d: %s", resp.StatusCode, body)
}

var users []User
if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
    log.Fatal(err)
}
// 20+ more lines for retry logic, error handling...

After (2 lines):

// httputil approach / httputil 방식
var users []User
err := httputil.Get("https://api.example.com/users", &users,
    httputil.WithBearerToken("token123"))
2. POST Request with Authentication / 인증과 함께 POST 요청
// Create payload / 페이로드 생성
payload := User{
    Name:  "John Doe",
    Email: "john@example.com",
}

// Send POST request / POST 요청 전송
var result Response
err := httputil.Post("https://api.example.com/users", payload, &result,
    httputil.WithBearerToken("your-token"),
    httputil.WithTimeout(30*time.Second))
if err != nil {
    log.Fatal(err)
}
3. Client with Base URL / Base URL을 가진 클라이언트
// Create configured client / 설정된 클라이언트 생성
client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com"),
    httputil.WithBearerToken("your-token"),
    httputil.WithRetry(5),
    httputil.WithTimeout(60*time.Second),
)

// Use client for multiple requests / 여러 요청에 클라이언트 사용
var users []User
err := client.Get("/users", &users)

var user User
err = client.Get("/users/123", &user)

payload := User{Name: "Jane"}
var created User
err = client.Post("/users", payload, &created)
4. Response Helpers / 응답 헬퍼
// Get raw response with helper methods / 헬퍼 메서드와 함께 원시 응답 가져오기
resp, err := httputil.DoRaw("GET", "https://api.example.com/users", nil,
    httputil.WithBearerToken("token123"))
if err != nil {
    log.Fatal(err)
}

// Check status / 상태 확인
if resp.IsSuccess() {
    log.Println("Request successful")
}

// Access body / 본문 접근
bodyString := resp.String()
bodyBytes := resp.Body()

// Decode JSON / JSON 디코딩
var users []User
err = resp.JSON(&users)
5. File Download with Progress / 진행 상황과 함께 파일 다운로드
// Download file with progress tracking / 진행 상황 추적과 함께 파일 다운로드
err := httputil.DownloadFile(
    "https://example.com/large-file.zip",
    "./downloads/file.zip",
    httputil.WithProgress(func(bytesRead, totalBytes int64) {
        progress := float64(bytesRead) / float64(totalBytes) * 100
        fmt.Printf("\rDownloading: %.2f%%", progress)
    }),
)
if err != nil {
    log.Fatal(err)
}
6. File Upload / 파일 업로드
// Upload single file / 단일 파일 업로드
var result map[string]interface{}
err := httputil.UploadFile(
    "https://api.example.com/upload",
    "file",
    "./document.pdf",
    &result,
    httputil.WithBearerToken("token123"),
)
if err != nil {
    log.Fatal(err)
}

// Upload multiple files / 여러 파일 업로드
err = httputil.UploadFiles(
    "https://api.example.com/upload-multiple",
    map[string]string{
        "file1": "./image1.jpg",
        "file2": "./image2.jpg",
    },
    &result,
    httputil.WithBearerToken("token123"),
)
7. URL Builder / URL 빌더
// Build URL with fluent API / Fluent API로 URL 구축
url := httputil.NewURL("https://api.example.com").
    Path("users", "search").
    Param("q", "golang").
    Param("page", "1").
    ParamIf(includeInactive, "status", "inactive").
    Build()
// Result: https://api.example.com/users/search?q=golang&page=1

// Join URL paths / URL 경로 결합
url = httputil.JoinURL("https://api.example.com", "v1", "users", "123")
// Result: https://api.example.com/v1/users/123
8. Form Builder / Form 빌더
// Build form data with fluent API / Fluent API로 폼 데이터 구축
form := httputil.NewForm().
    Set("username", "john").
    Set("email", "john@example.com").
    AddIf(hasPromoCode, "promo_code", "SAVE20").
    AddMultiple("tags", "go", "http", "api")

// Post form data / 폼 데이터 전송
var result map[string]interface{}
err := httputil.PostForm(
    "https://api.example.com/submit",
    form.Map(),
    &result,
)

API Reference / API 참조

Simple API / 간단한 API

Package-level convenience functions using a default client.

기본 클라이언트를 사용하는 패키지 레벨 편의 함수들.

GET Request / GET 요청
func Get(url string, result interface{}, opts ...Option) error
func GetContext(ctx context.Context, url string, result interface{}, opts ...Option) error

Example / 예제:

var data MyStruct
err := httputil.Get("https://api.example.com/data", &data)
POST Request / POST 요청
func Post(url string, body, result interface{}, opts ...Option) error
func PostContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error

Example / 예제:

payload := MyPayload{Name: "test"}
var response MyResponse
err := httputil.Post("https://api.example.com/create", payload, &response)
PUT Request / PUT 요청
func Put(url string, body, result interface{}, opts ...Option) error
func PutContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error

Example / 예제:

update := MyUpdate{ID: 1, Name: "updated"}
var response MyResponse
err := httputil.Put("https://api.example.com/update/1", update, &response)
PATCH Request / PATCH 요청
func Patch(url string, body, result interface{}, opts ...Option) error
func PatchContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error

Example / 예제:

patch := map[string]interface{}{"name": "patched"}
var response MyResponse
err := httputil.Patch("https://api.example.com/update/1", patch, &response)
DELETE Request / DELETE 요청
func Delete(url string, result interface{}, opts ...Option) error
func DeleteContext(ctx context.Context, url string, result interface{}, opts ...Option) error

Example / 예제:

var response MyResponse
err := httputil.Delete("https://api.example.com/delete/1", &response)
Set Default Client / 기본 클라이언트 설정
func SetDefaultClient(client *Client)

Configure the default client used by package-level functions.

패키지 레벨 함수에서 사용되는 기본 클라이언트를 설정합니다.

Example / 예제:

httputil.SetDefaultClient(httputil.NewClient(
    httputil.WithTimeout(60*time.Second),
    httputil.WithRetry(5),
))
Raw Response / 원시 응답
func DoRaw(method, url string, body interface{}, opts ...Option) (*Response, error)
func DoRawContext(ctx context.Context, method, url string, body interface{}, opts ...Option) (*Response, error)

Get raw Response with helper methods instead of auto-decoding JSON.

JSON 자동 디코딩 대신 헬퍼 메서드가 있는 원시 Response를 가져옵니다.

Example / 예제:

resp, err := httputil.DoRaw("GET", "https://api.example.com/data", nil)
if resp.IsSuccess() {
    bodyString := resp.String()
}
File Operations / 파일 작업
func DownloadFile(url, filepath string, opts ...Option) error
func DownloadFileContext(ctx context.Context, url, filepath string, progress ProgressFunc, opts ...Option) error
func Download(url string, opts ...Option) ([]byte, error)
func DownloadContext(ctx context.Context, url string, opts ...Option) ([]byte, error)

Download files from URL with optional progress tracking.

선택적 진행 상황 추적과 함께 URL에서 파일을 다운로드합니다.

Example / 예제:

// Download to file / 파일로 다운로드
err := httputil.DownloadFile("https://example.com/file.zip", "./file.zip")

// Download to memory / 메모리로 다운로드
data, err := httputil.Download("https://example.com/data.json")

// With progress callback / 진행 상황 콜백과 함께
ctx := context.Background()
err = httputil.DownloadFileContext(ctx, url, filepath,
    func(read, total int64) {
        fmt.Printf("Progress: %.2f%%\n", float64(read)/float64(total)*100)
    })
func UploadFile(url, fieldName, filepath string, result interface{}, opts ...Option) error
func UploadFileContext(ctx context.Context, url, fieldName, filepath string, result interface{}, opts ...Option) error
func UploadFiles(url string, files map[string]string, result interface{}, opts ...Option) error
func UploadFilesContext(ctx context.Context, url string, files map[string]string, result interface{}, opts ...Option) error

Upload files using multipart form data.

multipart form data를 사용하여 파일을 업로드합니다.

Example / 예제:

// Upload single file / 단일 파일 업로드
var result map[string]interface{}
err := httputil.UploadFile(url, "document", "./file.pdf", &result)

// Upload multiple files / 여러 파일 업로드
err = httputil.UploadFiles(url, map[string]string{
    "file1": "./image1.jpg",
    "file2": "./image2.jpg",
}, &result)
Form Operations / Form 작업
func PostForm(url string, data map[string]string, result interface{}, opts ...Option) error
func PostFormContext(ctx context.Context, url string, data map[string]string, result interface{}, opts ...Option) error

Post form data with application/x-www-form-urlencoded encoding.

application/x-www-form-urlencoded 인코딩으로 폼 데이터를 전송합니다.

Example / 예제:

var result map[string]interface{}
err := httputil.PostForm(url, map[string]string{
    "username": "john",
    "email": "john@example.com",
}, &result)

Client API

Create and configure custom HTTP clients.

사용자 정의 HTTP 클라이언트 생성 및 설정.

Create Client / 클라이언트 생성
func NewClient(opts ...Option) *Client

Example / 예제:

client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com"),
    httputil.WithBearerToken("token123"),
    httputil.WithRetry(3),
)
Client Methods / 클라이언트 메서드

All methods available on Client instances:

Client 인스턴스에서 사용 가능한 모든 메서드:

func (c *Client) Get(path string, result interface{}, opts ...Option) error
func (c *Client) GetContext(ctx context.Context, path string, result interface{}, opts ...Option) error

func (c *Client) Post(path string, body, result interface{}, opts ...Option) error
func (c *Client) PostContext(ctx context.Context, path string, body, result interface{}, opts ...Option) error

func (c *Client) Put(path string, body, result interface{}, opts ...Option) error
func (c *Client) PutContext(ctx context.Context, path string, body, result interface{}, opts ...Option) error

func (c *Client) Patch(path string, body, result interface{}, opts ...Option) error
func (c *Client) PatchContext(ctx context.Context, path string, body, result interface{}, opts ...Option) error

func (c *Client) Delete(path string, result interface{}, opts ...Option) error
func (c *Client) DeleteContext(ctx context.Context, path string, result interface{}, opts ...Option) error
Client File Operations / 클라이언트 파일 작업
func (c *Client) DownloadFile(url, filepath string, opts ...Option) error
func (c *Client) DownloadFileContext(ctx context.Context, url, filepath string, progress ProgressFunc, opts ...Option) error
func (c *Client) Download(url string, opts ...Option) ([]byte, error)
func (c *Client) DownloadContext(ctx context.Context, url string, opts ...Option) ([]byte, error)

func (c *Client) UploadFile(url, fieldName, filepath string, result interface{}, opts ...Option) error
func (c *Client) UploadFileContext(ctx context.Context, url, fieldName, filepath string, result interface{}, opts ...Option) error
func (c *Client) UploadFiles(url string, files map[string]string, result interface{}, opts ...Option) error
func (c *Client) UploadFilesContext(ctx context.Context, url string, files map[string]string, result interface{}, opts ...Option) error
Client Form Operations / 클라이언트 Form 작업
func (c *Client) PostForm(path string, data map[string]string, result interface{}, opts ...Option) error
func (c *Client) PostFormContext(ctx context.Context, path string, data map[string]string, result interface{}, opts ...Option) error

Response API / Response API

Rich response wrapper with helper methods for easier response handling.

더 쉬운 응답 처리를 위한 헬퍼 메서드가 있는 풍부한 응답 래퍼.

type Response struct {
    *http.Response
    // ... cached body
}
Body Methods / 본문 메서드
func (r *Response) Body() []byte                          // Get response body as bytes
func (r *Response) String() string                        // Get response body as string
func (r *Response) JSON(result interface{}) error         // Decode JSON into result

Example / 예제:

resp, _ := httputil.DoRaw("GET", url, nil)
bodyBytes := resp.Body()
bodyString := resp.String()

var data MyStruct
resp.JSON(&data)
Status Check Methods / 상태 확인 메서드
func (r *Response) IsSuccess() bool        // 2xx status codes
func (r *Response) IsError() bool          // 4xx or 5xx status codes
func (r *Response) IsClientError() bool    // 4xx status codes
func (r *Response) IsServerError() bool    // 5xx status codes

// Specific status codes / 특정 상태 코드
func (r *Response) IsOK() bool             // 200 OK
func (r *Response) IsCreated() bool        // 201 Created
func (r *Response) IsAccepted() bool       // 202 Accepted
func (r *Response) IsNoContent() bool      // 204 No Content
func (r *Response) IsMovedPermanently() bool    // 301 Moved Permanently
func (r *Response) IsFound() bool          // 302 Found
func (r *Response) IsBadRequest() bool     // 400 Bad Request
func (r *Response) IsUnauthorized() bool   // 401 Unauthorized
func (r *Response) IsForbidden() bool      // 403 Forbidden
func (r *Response) IsNotFound() bool       // 404 Not Found
func (r *Response) IsInternalServerError() bool  // 500 Internal Server Error

Example / 예제:

resp, _ := httputil.DoRaw("GET", url, nil)

if resp.IsSuccess() {
    log.Println("Request successful")
} else if resp.IsNotFound() {
    log.Println("Resource not found")
} else if resp.IsServerError() {
    log.Println("Server error")
}
Header Methods / 헤더 메서드
func (r *Response) Header(key string) string           // Get single header value
func (r *Response) Headers() map[string]string        // Get all headers as map
func (r *Response) ContentType() string               // Get Content-Type header

Example / 예제:

resp, _ := httputil.DoRaw("GET", url, nil)
contentType := resp.ContentType()
allHeaders := resp.Headers()
customHeader := resp.Header("X-Custom-Header")

URL Builder API / URL Builder API

Fluent API for building URLs with parameters.

매개변수와 함께 URL을 구축하기 위한 Fluent API.

type URLBuilder struct { /* ... */ }
Methods / 메서드
func NewURL(baseURL string) *URLBuilder
func (u *URLBuilder) Path(segments ...string) *URLBuilder
func (u *URLBuilder) Param(key, value string) *URLBuilder
func (u *URLBuilder) Params(params map[string]string) *URLBuilder
func (u *URLBuilder) ParamIf(condition bool, key, value string) *URLBuilder
func (u *URLBuilder) Build() string

Example / 예제:

// Build complex URL / 복잡한 URL 구축
url := httputil.NewURL("https://api.example.com").
    Path("v1", "users", "search").
    Param("q", "golang").
    Param("page", "1").
    Param("limit", "20").
    ParamIf(includeInactive, "status", "inactive").
    Build()

// Result: https://api.example.com/v1/users/search?q=golang&page=1&limit=20
URL Utility Functions / URL 유틸리티 함수
func JoinURL(baseURL string, paths ...string) string
func AddQueryParams(urlStr string, params map[string]string) (string, error)
func GetDomain(urlStr string) (string, error)
func GetScheme(urlStr string) (string, error)
func IsAbsoluteURL(urlStr string) bool
func NormalizeURL(urlStr string) string

Example / 예제:

// Join URL parts / URL 부분 결합
url := httputil.JoinURL("https://api.example.com", "v1", "users", "123")
// Result: https://api.example.com/v1/users/123

// Add query parameters / 쿼리 매개변수 추가
url, _ = httputil.AddQueryParams(url, map[string]string{
    "fields": "name,email",
})

// Get domain / 도메인 가져오기
domain, _ := httputil.GetDomain("https://api.example.com:8080/path")
// Result: api.example.com:8080

// Check if absolute / 절대 URL인지 확인
isAbsolute := httputil.IsAbsoluteURL("https://example.com")  // true
isAbsolute = httputil.IsAbsoluteURL("/relative/path")        // false

Form Builder API / Form Builder API

Fluent API for building form data.

폼 데이터를 구축하기 위한 Fluent API.

type FormBuilder struct { /* ... */ }
Methods / 메서드
func NewForm() *FormBuilder
func (f *FormBuilder) Add(key, value string) *FormBuilder
func (f *FormBuilder) Set(key, value string) *FormBuilder
func (f *FormBuilder) AddMultiple(key string, values ...string) *FormBuilder
func (f *FormBuilder) AddIf(condition bool, key, value string) *FormBuilder
func (f *FormBuilder) Get(key string) string
func (f *FormBuilder) GetAll(key string) []string
func (f *FormBuilder) Has(key string) bool
func (f *FormBuilder) Del(key string) *FormBuilder
func (f *FormBuilder) Clone() *FormBuilder
func (f *FormBuilder) Map() map[string]string
func (f *FormBuilder) Encode() string

Example / 예제:

// Build form with conditional fields / 조건부 필드가 있는 폼 구축
hasPromo := true
form := httputil.NewForm().
    Set("username", "john").
    Set("email", "john@example.com").
    Set("age", "30").
    AddIf(hasPromo, "promo_code", "SAVE20").
    AddIf(false, "referrer", "none").
    AddMultiple("tags", "go", "http", "api")

// Check if field exists / 필드 존재 확인
if form.Has("promo_code") {
    log.Println("Promo code applied")
}

// Get form data / 폼 데이터 가져오기
formMap := form.Map()
encoded := form.Encode()

// Clone form / 폼 복제
form2 := form.Clone().Set("email", "jane@example.com")
Form Utility Functions / Form 유틸리티 함수
func ParseForm(data string) (map[string]string, error)
func EncodeForm(data map[string]string) string

Example / 예제:

// Parse form data / 폼 데이터 파싱
formData, _ := httputil.ParseForm("name=John&city=Seoul&age=30")
// Result: map[string]string{"name": "John", "city": "Seoul", "age": "30"}

// Encode form data / 폼 데이터 인코딩
encoded := httputil.EncodeForm(map[string]string{
    "username": "john",
    "password": "secret",
})
// Result: "password=secret&username=john"

Configuration Options / 설정 옵션
Request Configuration / 요청 설정
Option / 옵션 Type / 타입 Default / 기본값 Description / 설명
WithTimeout(duration) time.Duration 30 seconds / 30초 Request timeout / 요청 타임아웃
WithHeaders(map) map[string]string Empty / 빈 맵 Custom headers / 사용자 정의 헤더
WithHeader(key, value) string, string - Single header / 단일 헤더
WithQueryParams(map) map[string]string Empty / 빈 맵 Query parameters / 쿼리 매개변수
WithUserAgent(agent) string "go-utils/httputil v{version}" User-Agent header
WithProgress(callback) ProgressFunc nil Progress callback for file operations / 파일 작업을 위한 진행 상황 콜백

Example / 예제:

err := httputil.Get(url, &result,
    httputil.WithTimeout(10*time.Second),
    httputil.WithHeader("X-Custom-Header", "value"),
    httputil.WithQueryParams(map[string]string{
        "page": "1",
        "limit": "100",
    }),
)
Authentication / 인증
Option / 옵션 Type / 타입 Description / 설명
WithBearerToken(token) string Bearer token authentication / Bearer 토큰 인증
WithBasicAuth(user, pass) string, string Basic authentication / 기본 인증

Example / 예제:

// Bearer token / Bearer 토큰
err := httputil.Get(url, &result,
    httputil.WithBearerToken("your-token-here"))

// Basic auth / 기본 인증
err := httputil.Get(url, &result,
    httputil.WithBasicAuth("username", "password"))
Retry Configuration / 재시도 설정
Option / 옵션 Type / 타입 Default / 기본값 Description / 설명
WithRetry(maxRetries) int 3 Maximum retry attempts / 최대 재시도 횟수
WithRetryBackoff(min, max) time.Duration, time.Duration 100ms, 5s Backoff time range / 백오프 시간 범위

Example / 예제:

err := httputil.Get(url, &result,
    httputil.WithRetry(5),
    httputil.WithRetryBackoff(200*time.Millisecond, 10*time.Second))
Client Configuration / 클라이언트 설정
Option / 옵션 Type / 타입 Default / 기본값 Description / 설명
WithBaseURL(baseURL) string Empty / 빈 문자열 Base URL for all requests / 모든 요청의 기본 URL
WithFollowRedirects(follow) bool true Follow HTTP redirects / HTTP 리디렉션 따르기
WithMaxRedirects(max) int 10 Maximum redirects / 최대 리디렉션 수

Example / 예제:

client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com/v1"),
    httputil.WithFollowRedirects(false),
)
Option / 옵션 Type / 타입 Description / 설명
WithCookies() - Enable in-memory cookie jar / 메모리 내 쿠키 저장소 활성화
WithPersistentCookies(filePath) string Enable persistent cookie jar with file storage / 파일 저장소를 사용한 지속성 쿠키 저장소 활성화
WithCookieJar(jar) http.CookieJar Use custom cookie jar / 사용자 정의 쿠키 저장소 사용

Example / 예제:

// In-memory cookies (temporary) / 메모리 내 쿠키 (임시)
client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com"),
    httputil.WithCookies(),
)

// Persistent cookies (saved to file) / 지속성 쿠키 (파일에 저장)
client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com"),
    httputil.WithPersistentCookies("cookies.json"),
)

// Cookie operations / 쿠키 작업
u, _ := url.Parse("https://api.example.com")
client.SetCookie(u, &http.Cookie{Name: "session", Value: "abc123"})
cookies := client.GetCookies(u)
client.SaveCookies() // Save to file (persistent jar only) / 파일에 저장 (지속성 저장소만)

Error Types / 에러 타입
HTTPError

HTTP error with status code and body.

상태 코드와 본문을 포함한 HTTP 에러.

type HTTPError struct {
    StatusCode int
    Status     string
    Body       string
    URL        string
    Method     string
}

Check and Handle / 확인 및 처리:

err := httputil.Get(url, &result)
if err != nil {
    if httputil.IsHTTPError(err) {
        statusCode := httputil.GetStatusCode(err)
        if statusCode == 404 {
            // Handle not found / 찾을 수 없음 처리
        }
    }
}
RetryError

Error after all retry attempts failed.

모든 재시도 시도 실패 후 에러.

type RetryError struct {
    Attempts int
    LastErr  error
    URL      string
    Method   string
}

Check and Handle / 확인 및 처리:

err := httputil.Get(url, &result)
if err != nil {
    if httputil.IsRetryError(err) {
        // All retries failed / 모든 재시도 실패
        retryErr := err.(*httputil.RetryError)
        log.Printf("Failed after %d attempts", retryErr.Attempts)
    }
}
TimeoutError

Request timeout error.

요청 타임아웃 에러.

type TimeoutError struct {
    URL    string
    Method string
}

Check and Handle / 확인 및 처리:

err := httputil.Get(url, &result)
if err != nil {
    if httputil.IsTimeoutError(err) {
        // Handle timeout / 타임아웃 처리
        log.Println("Request timed out")
    }
}

Usage Examples / 사용 예제

Example 1: REST API Client / REST API 클라이언트
package main

import (
    "log"
    "time"

    "github.com/arkd0ng/go-utils/httputil"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func main() {
    // Create API client / API 클라이언트 생성
    client := httputil.NewClient(
        httputil.WithBaseURL("https://jsonplaceholder.typicode.com"),
        httputil.WithTimeout(30*time.Second),
        httputil.WithRetry(3),
    )

    // GET: List users / GET: 사용자 목록
    var users []User
    if err := client.Get("/users", &users); err != nil {
        log.Fatal(err)
    }
    log.Printf("Found %d users", len(users))

    // GET: Single user / GET: 단일 사용자
    var user User
    if err := client.Get("/users/1", &user); err != nil {
        log.Fatal(err)
    }
    log.Printf("User: %+v", user)

    // POST: Create user / POST: 사용자 생성
    newUser := User{Name: "John Doe", Email: "john@example.com"}
    var created User
    if err := client.Post("/users", newUser, &created); err != nil {
        log.Fatal(err)
    }
    log.Printf("Created: %+v", created)

    // PUT: Update user / PUT: 사용자 업데이트
    updated := User{ID: 1, Name: "Jane Doe", Email: "jane@example.com"}
    var result User
    if err := client.Put("/users/1", updated, &result); err != nil {
        log.Fatal(err)
    }
    log.Printf("Updated: %+v", result)

    // DELETE: Delete user / DELETE: 사용자 삭제
    if err := client.Delete("/users/1", nil); err != nil {
        log.Fatal(err)
    }
    log.Println("Deleted successfully")
}
Example 2: Context and Timeout / Context 및 타임아웃
package main

import (
    "context"
    "log"
    "time"

    "github.com/arkd0ng/go-utils/httputil"
)

func main() {
    // Create context with timeout / 타임아웃이 있는 context 생성
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    var result map[string]interface{}
    err := httputil.GetContext(ctx, "https://api.example.com/slow", &result)
    if err != nil {
        if httputil.IsTimeoutError(err) {
            log.Println("Request timed out")
        } else {
            log.Fatal(err)
        }
    }
}
Example 3: Error Handling / 에러 처리
package main

import (
    "log"

    "github.com/arkd0ng/go-utils/httputil"
)

func main() {
    var result map[string]interface{}
    err := httputil.Get("https://api.example.com/endpoint", &result,
        httputil.WithRetry(3))

    if err != nil {
        // Check error type / 에러 타입 확인
        switch {
        case httputil.IsHTTPError(err):
            statusCode := httputil.GetStatusCode(err)
            log.Printf("HTTP error: %d", statusCode)

            // Handle specific status codes / 특정 상태 코드 처리
            if statusCode == 404 {
                log.Println("Resource not found")
            } else if statusCode >= 500 {
                log.Println("Server error")
            }

        case httputil.IsRetryError(err):
            log.Println("All retry attempts failed")

        case httputil.IsTimeoutError(err):
            log.Println("Request timed out")

        default:
            log.Printf("Unknown error: %v", err)
        }
        return
    }

    log.Printf("Success: %+v", result)
}
Example 4: Custom Headers and Query Parameters / 사용자 정의 헤더 및 쿼리 매개변수
package main

import (
    "log"

    "github.com/arkd0ng/go-utils/httputil"
)

func main() {
    var result map[string]interface{}
    err := httputil.Get("https://api.example.com/search", &result,
        httputil.WithQueryParams(map[string]string{
            "q":     "golang",
            "page":  "1",
            "limit": "20",
        }),
        httputil.WithHeaders(map[string]string{
            "X-API-Version": "v1",
            "X-Request-ID":  "12345",
        }),
        httputil.WithBearerToken("your-token"),
    )

    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Results: %+v", result)
}

Best Practices / 모범 사례

1. Use Client for Multiple Requests / 여러 요청에 클라이언트 사용

Create a client instance when making multiple requests to the same API.

동일한 API에 여러 요청을 할 때는 클라이언트 인스턴스를 생성하세요.

// Good: Reuse client / 좋음: 클라이언트 재사용
client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com"),
    httputil.WithBearerToken("token"),
)
client.Get("/users", &users)
client.Get("/posts", &posts)

// Bad: Create new client each time / 나쁨: 매번 새 클라이언트 생성
httputil.Get("https://api.example.com/users", &users, httputil.WithBearerToken("token"))
httputil.Get("https://api.example.com/posts", &posts, httputil.WithBearerToken("token"))
2. Use Context for Cancellation / 취소를 위해 Context 사용

Always use Context variants for long-running requests.

장시간 실행되는 요청에는 항상 Context 변형을 사용하세요.

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

err := httputil.GetContext(ctx, url, &result)
3. Handle Errors Appropriately / 에러를 적절히 처리

Check error types and handle them specifically.

에러 타입을 확인하고 구체적으로 처리하세요.

err := httputil.Get(url, &result)
if err != nil {
    if httputil.IsHTTPError(err) {
        // Handle HTTP errors / HTTP 에러 처리
    } else if httputil.IsTimeoutError(err) {
        // Handle timeouts / 타임아웃 처리
    }
}
4. Configure Retry Logic / 재시도 로직 설정

Adjust retry settings based on your needs.

필요에 따라 재시도 설정을 조정하세요.

// For critical operations / 중요한 작업의 경우
client := httputil.NewClient(
    httputil.WithRetry(5),
    httputil.WithRetryBackoff(500*time.Millisecond, 30*time.Second),
)

// For non-critical operations / 중요하지 않은 작업의 경우
client := httputil.NewClient(
    httputil.WithRetry(1),
)
5. Set Appropriate Timeouts / 적절한 타임아웃 설정

Always set timeouts to prevent hanging requests.

항상 타임아웃을 설정하여 요청이 멈추는 것을 방지하세요.

// Short timeout for health checks / 헬스 체크용 짧은 타임아웃
httputil.Get(url, &result, httputil.WithTimeout(5*time.Second))

// Longer timeout for complex operations / 복잡한 작업용 긴 타임아웃
httputil.Post(url, data, &result, httputil.WithTimeout(2*time.Minute))

Documentation / 문서

Additional Resources / 추가 자료
Package Documentation / 패키지 문서

View full package documentation:

전체 패키지 문서 보기:

go doc github.com/arkd0ng/go-utils/httputil
Examples / 예제

See the examples directory for complete working examples:

완전한 작동 예제는 examples 디렉토리를 참조하세요:

# Run httputil example / httputil 예제 실행
go run examples/httputil/main.go

Version History / 버전 히스토리

v1.10.002 - 2025-10-15

Phase 2-4 Features Added / 2-4단계 기능 추가

  • Response helpers (20+ methods) / 응답 헬퍼 (20개 이상 메서드)
  • File operations (download/upload with progress) / 파일 작업 (진행 상황과 함께 다운로드/업로드)
  • URL Builder (fluent API) / URL 빌더 (Fluent API)
  • Form Builder (fluent API) / Form 빌더 (Fluent API)
  • URL utilities (6 functions) / URL 유틸리티 (6개 함수)
  • Form utilities (2 functions) / Form 유틸리티 (2개 함수)
  • Extended Simple API (26+ functions) / 확장된 간단한 API (26개 이상 함수)
  • Comprehensive tests (13 tests, 43+ sub-tests) / 종합 테스트 (13개 테스트, 43개 이상 하위 테스트)
v1.10.001 - 2025-10-15

Initial Release / 초기 릴리스

  • Core HTTP client with retry logic / 재시도 로직을 가진 핵심 HTTP 클라이언트
  • Simple API (10 functions) / 간단한 API (10개 함수)
  • Options pattern (12 options) / 옵션 패턴 (12개 옵션)
  • Error types (3 types) / 에러 타입 (3개 타입)
  • Comprehensive tests / 종합 테스트

License / 라이선스

MIT License - See LICENSE file for details.

MIT 라이선스 - 자세한 내용은 LICENSE 파일을 참조하세요.


Contributing / 기여

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

기여를 환영합니다! 가이드라인은 CONTRIBUTING.md를 참조하세요.


Package Author / 패키지 작성자: arkd0ng Repository / 저장소: https://github.com/arkd0ng/go-utils Go Version / Go 버전: 1.18+

Documentation

Overview

Package httputil provides cookie management functionality httputil 패키지는 쿠키 관리 기능을 제공합니다

Package httputil provides extreme simplicity HTTP utilities for Go. 패키지 httputil은 Go를 위한 극도로 간단한 HTTP 유틸리티를 제공합니다.

This package reduces 30+ lines of repetitive HTTP code to just 2-3 lines with automatic JSON handling, retry logic, and type-safe operations.

이 패키지는 30줄 이상의 반복적인 HTTP 코드를 자동 JSON 처리, 재시도 로직, 타입 안전 작업을 통해 단 2-3줄로 줄입니다.

# Key Features 주요 기능

- Simple HTTP methods (GET, POST, PUT, PATCH, DELETE) 간단한 HTTP 메서드 - Automatic JSON encoding/decoding 자동 JSON 인코딩/디코딩 - Automatic retry with exponential backoff 지수 백오프를 사용한 자동 재시도 - Type-safe response parsing with generics 제네릭을 사용한 타입 안전 응답 파싱 - Context support for cancellation and timeouts 취소 및 타임아웃을 위한 Context 지원 - Rich error types with debugging information 디버깅 정보를 포함한 풍부한 에러 타입 - Zero external dependencies 외부 의존성 제로

# Quick Start 빠른 시작

Simple GET request:

var result MyStruct
err := httputil.Get("https://api.example.com/data", &result)
if err != nil {
    log.Fatal(err)
}

Simple POST request with options:

payload := MyPayload{Name: "test"}
var response MyResponse
err := httputil.Post("https://api.example.com/create", payload, &response,
    httputil.WithBearerToken("your-token"),
    httputil.WithTimeout(30*time.Second),
    httputil.WithRetry(3),
)

Using a client for multiple requests:

client := httputil.NewClient(
    httputil.WithBaseURL("https://api.example.com"),
    httputil.WithBearerToken("your-token"),
    httputil.WithRetry(3),
)

var result MyStruct
err := client.Get("/data", &result)

# Categories 카테고리

  • Simple HTTP Methods (10 functions): Get, Post, Put, Patch, Delete with Context variants
  • Request Builders (8 functions): Query params, headers, auth, form data
  • Response Helpers (10 functions): JSON parsing, status checking, body reading
  • Client Configuration (12 functions): Timeout, retry, proxy, TLS config
  • Download/Upload (6 functions): File download and upload with progress
  • Utilities (8 functions): URL building, query params, content type helpers

Total: ~54 functions across 6 categories

# Design Philosophy 설계 철학

"30 lines → 2-3 lines" - Extreme Simplicity

  • Auto everything: JSON handling, retries, error wrapping
  • Type-safe with generics
  • Zero configuration needed
  • Context support everywhere

# Version 버전

Current version: v1.10.004

# License 라이선스

MIT License

Index

Constants

This section is empty.

Variables

View Source
var Version = version.Get()

Version is the current version of the httputil package. Version은 httputil 패키지의 현재 버전입니다.

The version is automatically loaded from cfg/app.yaml at package initialization. If the version cannot be loaded, it defaults to "unknown".

버전은 패키지 초기화 시 cfg/app.yaml에서 자동으로 로드됩니다. 버전을 로드할 수 없는 경우 "unknown"으로 기본 설정됩니다.

Functions

func AddQueryParams

func AddQueryParams(urlStr string, params map[string]string) (string, error)

AddQueryParams adds query parameters to a URL. AddQueryParams는 URL에 쿼리 매개변수를 추가합니다.

func Delete

func Delete(url string, result interface{}, opts ...Option) error

Delete performs a DELETE request using the default client and decodes the JSON response into result. Delete는 기본 클라이언트를 사용하여 DELETE 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

Example:

var response MyResponse
err := httputil.Delete("https://api.example.com/delete/1", &response)
if err != nil {
    log.Fatal(err)
}

func DeleteContext

func DeleteContext(ctx context.Context, url string, result interface{}, opts ...Option) error

DeleteContext performs a DELETE request with context using the default client. DeleteContext는 기본 클라이언트를 사용하여 context와 함께 DELETE 요청을 수행합니다.

func Download

func Download(url string, opts ...Option) ([]byte, error)

Download downloads data using the default client. Download는 기본 클라이언트를 사용하여 데이터를 다운로드합니다.

func DownloadContext

func DownloadContext(ctx context.Context, url string, opts ...Option) ([]byte, error)

DownloadContext downloads data with context using the default client. DownloadContext는 기본 클라이언트를 사용하여 context와 함께 데이터를 다운로드합니다.

func DownloadFile

func DownloadFile(url, filepath string, opts ...Option) error

DownloadFile downloads a file using the default client. DownloadFile은 기본 클라이언트를 사용하여 파일을 다운로드합니다.

func DownloadFileContext

func DownloadFileContext(ctx context.Context, url, filepath string, progress ProgressFunc, opts ...Option) error

DownloadFileContext downloads a file with context using the default client. DownloadFileContext는 기본 클라이언트를 사용하여 context와 함께 파일을 다운로드합니다.

func EncodeForm

func EncodeForm(data map[string]string) string

EncodeForm encodes a map as URL-encoded form data. EncodeForm은 맵을 URL 인코딩된 폼 데이터로 인코딩합니다.

func Example

func Example()

Example demonstrates basic usage of the httputil package. Example은 httputil 패키지의 기본 사용법을 보여줍니다.

func Get

func Get(url string, result interface{}, opts ...Option) error

Get performs a GET request using the default client and decodes the JSON response into result. Get은 기본 클라이언트를 사용하여 GET 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

Example:

var result MyStruct
err := httputil.Get("https://api.example.com/data", &result)
if err != nil {
    log.Fatal(err)
}

With options 옵션 포함:

err := httputil.Get("https://api.example.com/data", &result,
    httputil.WithBearerToken("your-token"),
    httputil.WithTimeout(30*time.Second),
)

func GetAllQueryParams

func GetAllQueryParams(urlStr string) (map[string]string, error)

GetAllQueryParams returns all query parameters from URL. GetAllQueryParams는 URL에서 모든 쿼리 매개변수를 반환합니다.

func GetContext

func GetContext(ctx context.Context, url string, result interface{}, opts ...Option) error

GetContext performs a GET request with context using the default client. GetContext는 기본 클라이언트를 사용하여 context와 함께 GET 요청을 수행합니다.

func GetDomain

func GetDomain(urlStr string) (string, error)

GetDomain returns the domain from a URL. GetDomain은 URL에서 도메인을 반환합니다.

func GetPath

func GetPath(urlStr string) (string, error)

GetPath returns the path from a URL. GetPath는 URL에서 경로를 반환합니다.

func GetQueryParam

func GetQueryParam(urlStr, key string) (string, error)

GetQueryParam returns a query parameter value from URL. GetQueryParam은 URL에서 쿼리 매개변수 값을 반환합니다.

func GetScheme

func GetScheme(urlStr string) (string, error)

GetScheme returns the scheme from a URL (http, https, etc.). GetScheme은 URL에서 스키마를 반환합니다 (http, https 등).

func GetStatusCode

func GetStatusCode(err error) int

GetStatusCode extracts the status code from an HTTPError. Returns 0 if the error is not an HTTPError. GetStatusCode는 HTTPError에서 상태 코드를 추출합니다. 에러가 HTTPError가 아닌 경우 0을 반환합니다.

func IsAbsoluteURL

func IsAbsoluteURL(urlStr string) bool

IsAbsoluteURL checks if a URL is absolute (has scheme). IsAbsoluteURL은 URL이 절대 경로인지 확인합니다 (스키마가 있음).

func IsHTTPError

func IsHTTPError(err error) bool

IsHTTPError checks if an error is an HTTPError. IsHTTPError는 에러가 HTTPError인지 확인합니다.

func IsRetryError

func IsRetryError(err error) bool

IsRetryError checks if an error is a RetryError. IsRetryError는 에러가 RetryError인지 확인합니다.

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError checks if an error is a TimeoutError. IsTimeoutError는 에러가 TimeoutError인지 확인합니다.

func JoinURL

func JoinURL(baseURL string, paths ...string) string

JoinURL joins base URL with path segments. JoinURL은 기본 URL을 경로 세그먼트와 결합합니다.

func NormalizeURL

func NormalizeURL(urlStr string) string

NormalizeURL normalizes a URL (removes trailing slash, etc.). NormalizeURL은 URL을 정규화합니다 (후행 슬래시 제거 등).

func ParseForm

func ParseForm(data string) (map[string]string, error)

ParseForm parses URL-encoded form data into a map. ParseForm은 URL 인코딩된 폼 데이터를 맵으로 파싱합니다.

func ParseURL

func ParseURL(urlStr string) (*url.URL, error)

ParseURL parses a URL string and returns *url.URL. ParseURL은 URL 문자열을 파싱하고 *url.URL을 반환합니다.

func Patch

func Patch(url string, body, result interface{}, opts ...Option) error

Patch performs a PATCH request with body using the default client and decodes the JSON response into result. Patch는 기본 클라이언트를 사용하여 body와 함께 PATCH 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

Example:

payload := map[string]interface{}{"name": "patched"}
var response MyResponse
err := httputil.Patch("https://api.example.com/update/1", payload, &response)
if err != nil {
    log.Fatal(err)
}

func PatchContext

func PatchContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error

PatchContext performs a PATCH request with context using the default client. PatchContext는 기본 클라이언트를 사용하여 context와 함께 PATCH 요청을 수행합니다.

func Post

func Post(url string, body, result interface{}, opts ...Option) error

Post performs a POST request with body using the default client and decodes the JSON response into result. Post는 기본 클라이언트를 사용하여 body와 함께 POST 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

Example:

payload := MyPayload{Name: "test"}
var response MyResponse
err := httputil.Post("https://api.example.com/create", payload, &response)
if err != nil {
    log.Fatal(err)
}

With options 옵션 포함:

err := httputil.Post("https://api.example.com/create", payload, &response,
    httputil.WithBearerToken("your-token"),
    httputil.WithRetry(3),
)

func PostContext

func PostContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error

PostContext performs a POST request with context using the default client. PostContext는 기본 클라이언트를 사용하여 context와 함께 POST 요청을 수행합니다.

func PostForm

func PostForm(url string, data map[string]string, result interface{}, opts ...Option) error

PostForm performs a POST request with form data using the default client. PostForm은 기본 클라이언트를 사용하여 폼 데이터와 함께 POST 요청을 수행합니다.

func PostFormContext

func PostFormContext(ctx context.Context, url string, data map[string]string, result interface{}, opts ...Option) error

PostFormContext performs a POST request with form data and context using the default client. PostFormContext는 기본 클라이언트를 사용하여 context 및 폼 데이터와 함께 POST 요청을 수행합니다.

func Put

func Put(url string, body, result interface{}, opts ...Option) error

Put performs a PUT request with body using the default client and decodes the JSON response into result. Put은 기본 클라이언트를 사용하여 body와 함께 PUT 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

Example:

payload := MyPayload{ID: 1, Name: "updated"}
var response MyResponse
err := httputil.Put("https://api.example.com/update/1", payload, &response)
if err != nil {
    log.Fatal(err)
}

func PutContext

func PutContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error

PutContext performs a PUT request with context using the default client. PutContext는 기본 클라이언트를 사용하여 context와 함께 PUT 요청을 수행합니다.

func RemoveQueryParam

func RemoveQueryParam(urlStr, key string) (string, error)

RemoveQueryParam removes a query parameter from URL. RemoveQueryParam은 URL에서 쿼리 매개변수를 제거합니다.

func SetDefaultClient

func SetDefaultClient(client *Client)

SetDefaultClient sets the default client used by package-level functions. SetDefaultClient는 패키지 레벨 함수에서 사용되는 기본 클라이언트를 설정합니다.

This is useful if you want to configure the default client with custom options. 기본 클라이언트를 사용자 정의 옵션으로 구성하려는 경우 유용합니다.

Example:

httputil.SetDefaultClient(httputil.NewClient(
    httputil.WithTimeout(60*time.Second),
    httputil.WithRetry(5),
))

func UploadFile

func UploadFile(url, fieldName, filepath string, result interface{}, opts ...Option) error

UploadFile uploads a file using the default client. UploadFile은 기본 클라이언트를 사용하여 파일을 업로드합니다.

func UploadFileContext

func UploadFileContext(ctx context.Context, url, fieldName, filepath string, result interface{}, progress ProgressFunc, opts ...Option) error

UploadFileContext uploads a file with context using the default client. UploadFileContext는 기본 클라이언트를 사용하여 context와 함께 파일을 업로드합니다.

func UploadFiles

func UploadFiles(url string, files map[string]string, result interface{}, opts ...Option) error

UploadFiles uploads multiple files using the default client. UploadFiles는 기본 클라이언트를 사용하여 여러 파일을 업로드합니다.

func UploadFilesContext

func UploadFilesContext(ctx context.Context, url string, files map[string]string, result interface{}, opts ...Option) error

UploadFilesContext uploads multiple files with context using the default client. UploadFilesContext는 기본 클라이언트를 사용하여 context와 함께 여러 파일을 업로드합니다.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps http.Client with additional functionality. Client는 추가 기능을 가진 http.Client를 래핑합니다.

func NewClient

func NewClient(opts ...Option) *Client

NewClient creates a new HTTP client with the given options. NewClient는 주어진 옵션으로 새로운 HTTP 클라이언트를 생성합니다.

func (*Client) ClearCookies

func (c *Client) ClearCookies() error

ClearCookies removes all cookies from the client's cookie jar ClearCookies는 클라이언트의 쿠키 저장소에서 모든 쿠키를 제거합니다

func (*Client) Delete

func (c *Client) Delete(path string, result interface{}, opts ...Option) error

Delete performs a DELETE request and decodes the JSON response into result. Delete는 DELETE 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) DeleteContext

func (c *Client) DeleteContext(ctx context.Context, path string, result interface{}, opts ...Option) error

DeleteContext performs a DELETE request with context and decodes the JSON response into result. DeleteContext는 context와 함께 DELETE 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) DoRaw

func (c *Client) DoRaw(method, path string, body interface{}, opts ...Option) (*Response, error)

DoRaw performs an HTTP request and returns the raw response. DoRaw는 HTTP 요청을 수행하고 원시 응답을 반환합니다.

func (*Client) DoRawContext

func (c *Client) DoRawContext(ctx context.Context, method, path string, body interface{}, opts ...Option) (*Response, error)

DoRawContext performs an HTTP request with context and returns the raw response. DoRawContext는 context와 함께 HTTP 요청을 수행하고 원시 응답을 반환합니다.

func (*Client) Download

func (c *Client) Download(url string, opts ...Option) ([]byte, error)

Download downloads data from the given URL and returns it as bytes. Download는 주어진 URL에서 데이터를 다운로드하고 바이트로 반환합니다.

func (*Client) DownloadContext

func (c *Client) DownloadContext(ctx context.Context, url string, opts ...Option) ([]byte, error)

DownloadContext downloads data with context. DownloadContext는 context와 함께 데이터를 다운로드합니다.

func (*Client) DownloadFile

func (c *Client) DownloadFile(url, filePath string, opts ...Option) error

DownloadFile downloads a file from the given URL and saves it to the specified path. DownloadFile은 주어진 URL에서 파일을 다운로드하고 지정된 경로에 저장합니다.

func (*Client) DownloadFileContext

func (c *Client) DownloadFileContext(ctx context.Context, url, filePath string, progress ProgressFunc, opts ...Option) error

DownloadFileContext downloads a file with context and optional progress callback. DownloadFileContext는 context 및 선택적 진행 상황 콜백과 함께 파일을 다운로드합니다.

func (*Client) Get

func (c *Client) Get(path string, result interface{}, opts ...Option) error

Get performs a GET request and decodes the JSON response into result. Get은 GET 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) GetContext

func (c *Client) GetContext(ctx context.Context, path string, result interface{}, opts ...Option) error

GetContext performs a GET request with context and decodes the JSON response into result. GetContext는 context와 함께 GET 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) GetCookie

func (c *Client) GetCookie(u *url.URL, name string) *http.Cookie

GetCookie gets a specific cookie by name for a URL GetCookie는 URL에 대한 특정 쿠키를 이름으로 가져옵니다

func (*Client) GetCookies

func (c *Client) GetCookies(u *url.URL) []*http.Cookie

GetCookies returns cookies for a URL from the client's cookie jar GetCookies는 클라이언트의 쿠키 저장소에서 URL에 대한 쿠키를 반환합니다

func (*Client) HasCookie

func (c *Client) HasCookie(u *url.URL, name string) bool

HasCookie checks if a cookie exists for a URL HasCookie는 URL에 대한 쿠키가 존재하는지 확인합니다

func (*Client) LoadCookies

func (c *Client) LoadCookies() error

LoadCookies loads cookies from file if persistence is enabled LoadCookies는 지속성이 활성화된 경우 파일에서 쿠키를 로드합니다

func (*Client) Patch

func (c *Client) Patch(path string, body, result interface{}, opts ...Option) error

Patch performs a PATCH request with body and decodes the JSON response into result. Patch는 body와 함께 PATCH 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) PatchContext

func (c *Client) PatchContext(ctx context.Context, path string, body, result interface{}, opts ...Option) error

PatchContext performs a PATCH request with context, body and decodes the JSON response into result. PatchContext는 context, body와 함께 PATCH 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) Post

func (c *Client) Post(path string, body, result interface{}, opts ...Option) error

Post performs a POST request with body and decodes the JSON response into result. Post는 body와 함께 POST 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) PostContext

func (c *Client) PostContext(ctx context.Context, path string, body, result interface{}, opts ...Option) error

PostContext performs a POST request with context, body and decodes the JSON response into result. PostContext는 context, body와 함께 POST 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) PostForm

func (c *Client) PostForm(path string, data map[string]string, result interface{}, opts ...Option) error

PostForm performs a POST request with form data (application/x-www-form-urlencoded). PostForm은 폼 데이터와 함께 POST 요청을 수행합니다 (application/x-www-form-urlencoded).

func (*Client) PostFormContext

func (c *Client) PostFormContext(ctx context.Context, path string, data map[string]string, result interface{}, opts ...Option) error

PostFormContext performs a POST request with form data and context. PostFormContext는 폼 데이터 및 context와 함께 POST 요청을 수행합니다.

func (*Client) Put

func (c *Client) Put(path string, body, result interface{}, opts ...Option) error

Put performs a PUT request with body and decodes the JSON response into result. Put은 body와 함께 PUT 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) PutContext

func (c *Client) PutContext(ctx context.Context, path string, body, result interface{}, opts ...Option) error

PutContext performs a PUT request with context, body and decodes the JSON response into result. PutContext는 context, body와 함께 PUT 요청을 수행하고 JSON 응답을 result로 디코딩합니다.

func (*Client) SaveCookies

func (c *Client) SaveCookies() error

SaveCookies saves cookies to file if persistence is enabled SaveCookies는 지속성이 활성화된 경우 쿠키를 파일에 저장합니다

func (*Client) SetCookie

func (c *Client) SetCookie(u *url.URL, cookie *http.Cookie)

SetCookie sets a cookie for a URL in the client's cookie jar SetCookie는 클라이언트의 쿠키 저장소에서 URL에 대한 쿠키를 설정합니다

func (*Client) UploadFile

func (c *Client) UploadFile(url, fieldName, filePath string, result interface{}, opts ...Option) error

UploadFile uploads a file to the given URL using multipart/form-data. UploadFile은 multipart/form-data를 사용하여 주어진 URL에 파일을 업로드합니다.

func (*Client) UploadFileContext

func (c *Client) UploadFileContext(ctx context.Context, url, fieldName, filePath string, result interface{}, progress ProgressFunc, opts ...Option) error

UploadFileContext uploads a file with context and optional progress callback. UploadFileContext는 context 및 선택적 진행 상황 콜백과 함께 파일을 업로드합니다.

func (*Client) UploadFiles

func (c *Client) UploadFiles(url string, files map[string]string, result interface{}, opts ...Option) error

UploadFiles uploads multiple files to the given URL using multipart/form-data. UploadFiles는 multipart/form-data를 사용하여 주어진 URL에 여러 파일을 업로드합니다.

func (*Client) UploadFilesContext

func (c *Client) UploadFilesContext(ctx context.Context, url string, files map[string]string, result interface{}, opts ...Option) error

UploadFilesContext uploads multiple files with context. UploadFilesContext는 context와 함께 여러 파일을 업로드합니다.

type CookieJar

type CookieJar struct {
	// contains filtered or unexported fields
}

CookieJar manages HTTP cookies with optional persistence CookieJar는 선택적 지속성과 함께 HTTP 쿠키를 관리합니다

func NewCookieJar

func NewCookieJar() (*CookieJar, error)

NewCookieJar creates a new cookie jar NewCookieJar는 새 쿠키 저장소를 생성합니다

func NewPersistentCookieJar

func NewPersistentCookieJar(filePath string) (*CookieJar, error)

NewPersistentCookieJar creates a cookie jar with file persistence NewPersistentCookieJar는 파일 지속성이 있는 쿠키 저장소를 생성합니다

func (*CookieJar) ClearCookies

func (cj *CookieJar) ClearCookies() error

ClearCookies removes all cookies ClearCookies는 모든 쿠키를 제거합니다

func (*CookieJar) Cookies

func (cj *CookieJar) Cookies(u *url.URL) []*http.Cookie

Cookies returns cookies for a URL Cookies는 URL에 대한 쿠키를 반환합니다

func (*CookieJar) CountCookies

func (cj *CookieJar) CountCookies(u *url.URL) int

CountCookies returns the total number of cookies for a URL CountCookies는 URL에 대한 총 쿠키 수를 반환합니다

func (*CookieJar) GetCookie

func (cj *CookieJar) GetCookie(u *url.URL, name string) *http.Cookie

GetCookie gets a specific cookie by name for a URL GetCookie는 URL에 대한 특정 쿠키를 이름으로 가져옵니다

func (*CookieJar) GetCookies

func (cj *CookieJar) GetCookies(u *url.URL) []*http.Cookie

GetCookies returns all cookies for a URL GetCookies는 URL에 대한 모든 쿠키를 반환합니다

func (*CookieJar) GetCookiesByDomain

func (cj *CookieJar) GetCookiesByDomain(domain string) []*http.Cookie

GetCookiesByDomain returns all cookies for a specific domain GetCookiesByDomain은 특정 도메인에 대한 모든 쿠키를 반환합니다

func (*CookieJar) HasCookie

func (cj *CookieJar) HasCookie(u *url.URL, name string) bool

HasCookie checks if a cookie exists for a URL HasCookie는 URL에 대한 쿠키가 존재하는지 확인합니다

func (*CookieJar) LoadCookies

func (cj *CookieJar) LoadCookies() error

LoadCookies loads cookies from file LoadCookies는 파일에서 쿠키를 로드합니다

func (*CookieJar) RemoveCookie

func (cj *CookieJar) RemoveCookie(u *url.URL, name string)

RemoveCookie removes a specific cookie by name for a URL RemoveCookie는 URL에 대한 특정 쿠키를 이름으로 제거합니다

func (*CookieJar) SaveCookies

func (cj *CookieJar) SaveCookies() error

SaveCookies saves cookies to file (JSON format) SaveCookies는 쿠키를 파일에 저장합니다 (JSON 형식)

func (*CookieJar) SetCookie

func (cj *CookieJar) SetCookie(u *url.URL, cookie *http.Cookie)

SetCookie sets a single cookie for a URL SetCookie는 URL에 대한 단일 쿠키를 설정합니다

func (*CookieJar) SetCookies

func (cj *CookieJar) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies sets cookies for a URL SetCookies는 URL에 대한 쿠키를 설정합니다

type FormBuilder

type FormBuilder struct {
	// contains filtered or unexported fields
}

FormBuilder helps build form data. FormBuilder는 폼 데이터를 구축하는 데 도움을 줍니다.

func NewForm

func NewForm() *FormBuilder

NewForm creates a new form builder. NewForm은 새 폼 빌더를 생성합니다.

func (*FormBuilder) Add

func (f *FormBuilder) Add(key, value string) *FormBuilder

Add adds a field to the form. Add는 폼에 필드를 추가합니다.

func (*FormBuilder) AddIf

func (f *FormBuilder) AddIf(condition bool, key, value string) *FormBuilder

AddIf adds a field if the condition is true. AddIf는 조건이 참이면 필드를 추가합니다.

func (*FormBuilder) AddMultiple

func (f *FormBuilder) AddMultiple(key string, values ...string) *FormBuilder

AddMultiple adds multiple values for the same key. AddMultiple은 동일한 키에 대해 여러 값을 추가합니다.

func (*FormBuilder) Clear

func (f *FormBuilder) Clear() *FormBuilder

Clear removes all fields from the form. Clear는 폼에서 모든 필드를 제거합니다.

func (*FormBuilder) Clone

func (f *FormBuilder) Clone() *FormBuilder

Clone creates a copy of the form builder. Clone은 폼 빌더의 복사본을 생성합니다.

func (*FormBuilder) Delete

func (f *FormBuilder) Delete(key string) *FormBuilder

Delete removes a field from the form. Delete는 폼에서 필드를 제거합니다.

func (*FormBuilder) Encode

func (f *FormBuilder) Encode() string

Encode returns the form data as URL-encoded string. Encode는 폼 데이터를 URL 인코딩된 문자열로 반환합니다.

func (*FormBuilder) Get

func (f *FormBuilder) Get(key string) string

Get returns the value of a field. Get은 필드의 값을 반환합니다.

func (*FormBuilder) GetAll

func (f *FormBuilder) GetAll(key string) []string

GetAll returns all values for a field. GetAll은 필드의 모든 값을 반환합니다.

func (*FormBuilder) Has

func (f *FormBuilder) Has(key string) bool

Has checks if a field exists in the form. Has는 폼에 필드가 있는지 확인합니다.

func (*FormBuilder) Map

func (f *FormBuilder) Map() map[string]string

Map returns the form data as a map (first value only). Map은 폼 데이터를 맵으로 반환합니다 (첫 번째 값만).

func (*FormBuilder) Set

func (f *FormBuilder) Set(key, value string) *FormBuilder

Set sets a field in the form (replaces existing value). Set은 폼에 필드를 설정합니다 (기존 값 교체).

func (*FormBuilder) String

func (f *FormBuilder) String() string

String returns the form data as URL-encoded string (same as Encode). String은 폼 데이터를 URL 인코딩된 문자열로 반환합니다 (Encode와 동일).

func (*FormBuilder) Values

func (f *FormBuilder) Values() url.Values

Values returns the underlying url.Values. Values는 기본 url.Values를 반환합니다.

type HTTPError

type HTTPError struct {
	// HTTP status code
	// HTTP 상태 코드
	StatusCode int
	// HTTP status text
	// HTTP 상태 텍스트
	Status string
	// Response body
	// 응답 본문
	Body string
	// Request URL
	// 요청 URL
	URL string
	// HTTP method
	// HTTP 메서드
	Method string
}

HTTPError represents an HTTP error with status code and response details. HTTPError는 상태 코드 및 응답 세부 정보를 포함하는 HTTP 에러를 나타냅니다.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface. Error는 error 인터페이스를 구현합니다.

type Logger

type Logger interface {
	// Log logs a message with key-value pairs
	// Log는 키-값 쌍과 함께 메시지를 로깅합니다
	Log(msg string, keysAndValues ...interface{})
}

Logger is an interface for logging HTTP requests and responses. Logger는 HTTP 요청 및 응답을 로깅하기 위한 인터페이스입니다.

type Option

type Option func(*config)

Option is a functional option for configuring HTTP requests and clients. Option은 HTTP 요청 및 클라이언트를 설정하기 위한 함수형 옵션입니다.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the base URL for the client. WithBaseURL은 클라이언트의 기본 URL을 설정합니다.

This is useful when making multiple requests to the same API. 동일한 API에 여러 요청을 할 때 유용합니다.

func WithBasicAuth

func WithBasicAuth(username, password string) Option

WithBasicAuth sets Basic Authentication credentials. WithBasicAuth는 기본 인증 자격 증명을 설정합니다.

func WithBearerToken

func WithBearerToken(token string) Option

WithBearerToken sets the Bearer token for authentication. WithBearerToken은 인증을 위한 Bearer 토큰을 설정합니다.

func WithCookieJar

func WithCookieJar(jar http.CookieJar) Option

WithCookieJar sets a custom cookie jar. WithCookieJar는 사용자 정의 쿠키 저장소를 설정합니다.

func WithCookies

func WithCookies() Option

WithCookies enables cookie management with an in-memory cookie jar. WithCookies는 메모리 내 쿠키 저장소를 사용한 쿠키 관리를 활성화합니다.

This creates a temporary cookie jar that will be discarded when the client is closed. 이는 클라이언트가 닫힐 때 삭제되는 임시 쿠키 저장소를 생성합니다.

For persistent cookies, use WithPersistentCookies instead. 지속적인 쿠키를 위해서는 WithPersistentCookies를 사용하세요.

func WithFollowRedirects

func WithFollowRedirects(follow bool) Option

WithFollowRedirects enables or disables following HTTP redirects. WithFollowRedirects는 HTTP 리디렉션 따르기를 활성화하거나 비활성화합니다.

Default: true 기본값: true

func WithHeader

func WithHeader(key, value string) Option

WithHeader sets a single custom header for the request. WithHeader는 요청에 대한 단일 사용자 정의 헤더를 설정합니다.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders sets custom headers for the request. WithHeaders는 요청에 대한 사용자 정의 헤더를 설정합니다.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets a custom logger. WithLogger는 사용자 정의 로거를 설정합니다.

func WithMaxRedirects

func WithMaxRedirects(max int) Option

WithMaxRedirects sets the maximum number of redirects to follow. WithMaxRedirects는 따를 최대 리디렉션 수를 설정합니다.

Default: 10 기본값: 10

func WithPersistentCookies

func WithPersistentCookies(filePath string) Option

WithPersistentCookies enables cookie management with file persistence. WithPersistentCookies는 파일 지속성을 가진 쿠키 관리를 활성화합니다.

Cookies will be automatically saved to and loaded from the specified file path. 쿠키는 지정된 파일 경로에 자동으로 저장되고 로드됩니다.

Example:

client := httputil.NewClient(
    httputil.WithPersistentCookies("cookies.json"),
)

func WithProxy

func WithProxy(proxyURL string) Option

WithProxy sets the proxy URL. WithProxy는 프록시 URL을 설정합니다.

func WithQueryParams

func WithQueryParams(params map[string]string) Option

WithQueryParams sets query parameters for the request. WithQueryParams는 요청에 대한 쿼리 매개변수를 설정합니다.

func WithRetry

func WithRetry(maxRetries int) Option

WithRetry sets the maximum number of retry attempts. WithRetry는 최대 재시도 시도 횟수를 설정합니다.

Default: 3 기본값: 3

func WithRetryBackoff

func WithRetryBackoff(min, max time.Duration) Option

WithRetryBackoff sets the minimum and maximum backoff time for retries. WithRetryBackoff는 재시도에 대한 최소 및 최대 백오프 시간을 설정합니다.

Default: min=100ms, max=5s 기본값: min=100ms, max=5s

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) Option

WithTLSConfig sets a custom TLS configuration. WithTLSConfig는 사용자 정의 TLS 설정을 지정합니다.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the request timeout. WithTimeout은 요청 타임아웃을 설정합니다.

Default: 30 seconds 기본값: 30초

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent sets a custom User-Agent header. WithUserAgent는 사용자 정의 User-Agent 헤더를 설정합니다.

Default: "go-utils/httputil v{version}" 기본값: "go-utils/httputil v{version}"

type ProgressFunc

type ProgressFunc func(bytesRead, totalBytes int64)

ProgressFunc is a callback function for tracking progress. ProgressFunc는 진행 상황을 추적하기 위한 콜백 함수입니다.

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response wraps http.Response with additional functionality. Response는 추가 기능을 가진 http.Response를 래핑합니다.

func DoRaw

func DoRaw(method, url string, body interface{}, opts ...Option) (*Response, error)

DoRaw performs an HTTP request and returns the raw response using the default client. DoRaw는 기본 클라이언트를 사용하여 HTTP 요청을 수행하고 원시 응답을 반환합니다.

func DoRawContext

func DoRawContext(ctx context.Context, method, url string, body interface{}, opts ...Option) (*Response, error)

DoRawContext performs an HTTP request with context and returns the raw response using the default client. DoRawContext는 기본 클라이언트를 사용하여 context와 함께 HTTP 요청을 수행하고 원시 응답을 반환합니다.

func (*Response) Body

func (r *Response) Body() []byte

Body returns the response body as bytes. Body는 응답 본문을 바이트로 반환합니다.

func (*Response) ContentLength

func (r *Response) ContentLength() int64

ContentLength returns the Content-Length header value. ContentLength는 Content-Length 헤더 값을 반환합니다.

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the Content-Type header value. ContentType은 Content-Type 헤더 값을 반환합니다.

func (*Response) Header

func (r *Response) Header(key string) string

Header returns the value of the header with the given key. Header는 주어진 키의 헤더 값을 반환합니다.

func (*Response) Headers

func (r *Response) Headers() map[string]string

Headers returns all headers as a map. Headers는 모든 헤더를 맵으로 반환합니다.

func (*Response) IsBadGateway

func (r *Response) IsBadGateway() bool

IsBadGateway returns true if status code is 502. IsBadGateway는 상태 코드가 502이면 true를 반환합니다.

func (*Response) IsBadRequest

func (r *Response) IsBadRequest() bool

IsBadRequest returns true if status code is 400. IsBadRequest는 상태 코드가 400이면 true를 반환합니다.

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError returns true if status code is 4xx. IsClientError는 상태 코드가 4xx이면 true를 반환합니다.

func (*Response) IsCreated

func (r *Response) IsCreated() bool

IsCreated returns true if status code is 201. IsCreated는 상태 코드가 201이면 true를 반환합니다.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if status code is 4xx or 5xx. IsError는 상태 코드가 4xx 또는 5xx이면 true를 반환합니다.

func (*Response) IsForbidden

func (r *Response) IsForbidden() bool

IsForbidden returns true if status code is 403. IsForbidden는 상태 코드가 403이면 true를 반환합니다.

func (*Response) IsGatewayTimeout

func (r *Response) IsGatewayTimeout() bool

IsGatewayTimeout returns true if status code is 504. IsGatewayTimeout는 상태 코드가 504이면 true를 반환합니다.

func (*Response) IsInternalServerError

func (r *Response) IsInternalServerError() bool

IsInternalServerError returns true if status code is 500. IsInternalServerError는 상태 코드가 500이면 true를 반환합니다.

func (*Response) IsNoContent

func (r *Response) IsNoContent() bool

IsNoContent returns true if status code is 204. IsNoContent는 상태 코드가 204이면 true를 반환합니다.

func (*Response) IsNotFound

func (r *Response) IsNotFound() bool

IsNotFound returns true if status code is 404. IsNotFound는 상태 코드가 404이면 true를 반환합니다.

func (*Response) IsOK

func (r *Response) IsOK() bool

IsOK returns true if status code is 200. IsOK는 상태 코드가 200이면 true를 반환합니다.

func (*Response) IsRedirect

func (r *Response) IsRedirect() bool

IsRedirect returns true if status code is 3xx. IsRedirect는 상태 코드가 3xx이면 true를 반환합니다.

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError returns true if status code is 5xx. IsServerError는 상태 코드가 5xx이면 true를 반환합니다.

func (*Response) IsServiceUnavailable

func (r *Response) IsServiceUnavailable() bool

IsServiceUnavailable returns true if status code is 503. IsServiceUnavailable는 상태 코드가 503이면 true를 반환합니다.

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if status code is 2xx. IsSuccess는 상태 코드가 2xx이면 true를 반환합니다.

func (*Response) IsTooManyRequests

func (r *Response) IsTooManyRequests() bool

IsTooManyRequests returns true if status code is 429. IsTooManyRequests는 상태 코드가 429이면 true를 반환합니다.

func (*Response) IsUnauthorized

func (r *Response) IsUnauthorized() bool

IsUnauthorized returns true if status code is 401. IsUnauthorized는 상태 코드가 401이면 true를 반환합니다.

func (*Response) JSON

func (r *Response) JSON(result interface{}) error

JSON decodes the response body as JSON into result. JSON은 응답 본문을 JSON으로 result에 디코딩합니다.

func (*Response) String

func (r *Response) String() string

String returns the response body as string. String은 응답 본문을 문자열로 반환합니다.

type RetryError

type RetryError struct {
	// Number of retry attempts
	// 재시도 시도 횟수
	Attempts int
	// Last error encountered
	// 마지막으로 발생한 에러
	LastErr error
	// Request URL
	// 요청 URL
	URL string
	// HTTP method
	// HTTP 메서드
	Method string
}

RetryError represents an error after all retry attempts have failed. RetryError는 모든 재시도 시도가 실패한 후의 에러를 나타냅니다.

func (*RetryError) Error

func (e *RetryError) Error() string

Error implements the error interface. Error는 error 인터페이스를 구현합니다.

func (*RetryError) Unwrap

func (e *RetryError) Unwrap() error

Unwrap returns the last error for error unwrapping. Unwrap은 에러 언래핑을 위해 마지막 에러를 반환합니다.

type TimeoutError

type TimeoutError struct {
	// Request URL
	// 요청 URL
	URL string
	// HTTP method
	// HTTP 메서드
	Method string
}

TimeoutError represents a timeout error. TimeoutError는 타임아웃 에러를 나타냅니다.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface. Error는 error 인터페이스를 구현합니다.

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Timeout returns true to indicate this is a timeout error. Timeout은 이것이 타임아웃 에러임을 나타내기 위해 true를 반환합니다.

type URLBuilder

type URLBuilder struct {
	// contains filtered or unexported fields
}

URLBuilder helps build URLs with path and query parameters. URLBuilder는 경로 및 쿼리 매개변수로 URL을 구축하는 데 도움을 줍니다.

func NewURL

func NewURL(baseURL string) *URLBuilder

NewURL creates a new URL builder with the given base URL. NewURL은 주어진 기본 URL로 새 URL 빌더를 생성합니다.

func (*URLBuilder) Build

func (u *URLBuilder) Build() string

Build returns the final URL string. Build는 최종 URL 문자열을 반환합니다.

func (*URLBuilder) Param

func (u *URLBuilder) Param(key, value string) *URLBuilder

Param adds a query parameter to the URL. Param은 URL에 쿼리 매개변수를 추가합니다.

func (*URLBuilder) ParamIf

func (u *URLBuilder) ParamIf(condition bool, key, value string) *URLBuilder

ParamIf adds a query parameter if the condition is true. ParamIf는 조건이 참이면 쿼리 매개변수를 추가합니다.

func (*URLBuilder) Params

func (u *URLBuilder) Params(params map[string]string) *URLBuilder

Params adds multiple query parameters to the URL. Params는 URL에 여러 쿼리 매개변수를 추가합니다.

func (*URLBuilder) Path

func (u *URLBuilder) Path(segments ...string) *URLBuilder

Path adds path segments to the URL. Path는 URL에 경로 세그먼트를 추가합니다.

func (*URLBuilder) String

func (u *URLBuilder) String() string

String returns the final URL string (same as Build). String은 최종 URL 문자열을 반환합니다 (Build와 동일).

Jump to

Keyboard shortcuts

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