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 ¶
- Variables
- func AddQueryParams(urlStr string, params map[string]string) (string, error)
- func Delete(url string, result interface{}, opts ...Option) error
- func DeleteContext(ctx context.Context, url string, result interface{}, opts ...Option) error
- func Download(url string, opts ...Option) ([]byte, error)
- func DownloadContext(ctx context.Context, url string, opts ...Option) ([]byte, error)
- func DownloadFile(url, filepath string, opts ...Option) error
- func DownloadFileContext(ctx context.Context, url, filepath string, progress ProgressFunc, ...) error
- func EncodeForm(data map[string]string) string
- func Example()
- func Get(url string, result interface{}, opts ...Option) error
- func GetAllQueryParams(urlStr string) (map[string]string, error)
- func GetContext(ctx context.Context, url string, result interface{}, opts ...Option) error
- func GetDomain(urlStr string) (string, error)
- func GetPath(urlStr string) (string, error)
- func GetQueryParam(urlStr, key string) (string, error)
- func GetScheme(urlStr string) (string, error)
- func GetStatusCode(err error) int
- func IsAbsoluteURL(urlStr string) bool
- func IsHTTPError(err error) bool
- func IsRetryError(err error) bool
- func IsTimeoutError(err error) bool
- func JoinURL(baseURL string, paths ...string) string
- func NormalizeURL(urlStr string) string
- func ParseForm(data string) (map[string]string, error)
- func ParseURL(urlStr string) (*url.URL, error)
- func Patch(url string, body, result interface{}, opts ...Option) error
- func PatchContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error
- func Post(url string, body, result interface{}, opts ...Option) error
- func PostContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error
- 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{}, ...) error
- func Put(url string, body, result interface{}, opts ...Option) error
- func PutContext(ctx context.Context, url string, body, result interface{}, opts ...Option) error
- func RemoveQueryParam(urlStr, key string) (string, error)
- func SetDefaultClient(client *Client)
- func UploadFile(url, fieldName, filepath string, result interface{}, opts ...Option) error
- func UploadFileContext(ctx context.Context, url, fieldName, filepath string, result interface{}, ...) 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{}, ...) error
- type Client
- func (c *Client) ClearCookies() 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
- func (c *Client) DoRaw(method, path string, body interface{}, opts ...Option) (*Response, error)
- func (c *Client) DoRawContext(ctx context.Context, method, path string, body interface{}, opts ...Option) (*Response, 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) DownloadFile(url, filePath string, opts ...Option) error
- func (c *Client) DownloadFileContext(ctx context.Context, url, filePath string, progress ProgressFunc, ...) error
- 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) GetCookie(u *url.URL, name string) *http.Cookie
- func (c *Client) GetCookies(u *url.URL) []*http.Cookie
- func (c *Client) HasCookie(u *url.URL, name string) bool
- func (c *Client) LoadCookies() 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) 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) 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{}, ...) 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) SaveCookies() error
- func (c *Client) SetCookie(u *url.URL, cookie *http.Cookie)
- 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{}, ...) 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{}, ...) error
- type CookieJar
- func (cj *CookieJar) ClearCookies() error
- func (cj *CookieJar) Cookies(u *url.URL) []*http.Cookie
- func (cj *CookieJar) CountCookies(u *url.URL) int
- func (cj *CookieJar) GetCookie(u *url.URL, name string) *http.Cookie
- func (cj *CookieJar) GetCookies(u *url.URL) []*http.Cookie
- func (cj *CookieJar) GetCookiesByDomain(domain string) []*http.Cookie
- func (cj *CookieJar) HasCookie(u *url.URL, name string) bool
- func (cj *CookieJar) LoadCookies() error
- func (cj *CookieJar) RemoveCookie(u *url.URL, name string)
- func (cj *CookieJar) SaveCookies() error
- func (cj *CookieJar) SetCookie(u *url.URL, cookie *http.Cookie)
- func (cj *CookieJar) SetCookies(u *url.URL, cookies []*http.Cookie)
- type FormBuilder
- func (f *FormBuilder) Add(key, value string) *FormBuilder
- func (f *FormBuilder) AddIf(condition bool, key, value string) *FormBuilder
- func (f *FormBuilder) AddMultiple(key string, values ...string) *FormBuilder
- func (f *FormBuilder) Clear() *FormBuilder
- func (f *FormBuilder) Clone() *FormBuilder
- func (f *FormBuilder) Delete(key string) *FormBuilder
- func (f *FormBuilder) Encode() string
- func (f *FormBuilder) Get(key string) string
- func (f *FormBuilder) GetAll(key string) []string
- func (f *FormBuilder) Has(key string) bool
- func (f *FormBuilder) Map() map[string]string
- func (f *FormBuilder) Set(key, value string) *FormBuilder
- func (f *FormBuilder) String() string
- func (f *FormBuilder) Values() url.Values
- type HTTPError
- type Logger
- type Option
- func WithBaseURL(baseURL string) Option
- func WithBasicAuth(username, password string) Option
- func WithBearerToken(token string) Option
- func WithCookieJar(jar http.CookieJar) Option
- func WithCookies() Option
- func WithFollowRedirects(follow bool) Option
- func WithHeader(key, value string) Option
- func WithHeaders(headers map[string]string) Option
- func WithLogger(logger Logger) Option
- func WithMaxRedirects(max int) Option
- func WithPersistentCookies(filePath string) Option
- func WithProxy(proxyURL string) Option
- func WithQueryParams(params map[string]string) Option
- func WithRetry(maxRetries int) Option
- func WithRetryBackoff(min, max time.Duration) Option
- func WithTLSConfig(tlsConfig *tls.Config) Option
- func WithTimeout(timeout time.Duration) Option
- func WithUserAgent(userAgent string) Option
- type ProgressFunc
- type Response
- func (r *Response) Body() []byte
- func (r *Response) ContentLength() int64
- func (r *Response) ContentType() string
- func (r *Response) Header(key string) string
- func (r *Response) Headers() map[string]string
- func (r *Response) IsBadGateway() bool
- func (r *Response) IsBadRequest() bool
- func (r *Response) IsClientError() bool
- func (r *Response) IsCreated() bool
- func (r *Response) IsError() bool
- func (r *Response) IsForbidden() bool
- func (r *Response) IsGatewayTimeout() bool
- func (r *Response) IsInternalServerError() bool
- func (r *Response) IsNoContent() bool
- func (r *Response) IsNotFound() bool
- func (r *Response) IsOK() bool
- func (r *Response) IsRedirect() bool
- func (r *Response) IsServerError() bool
- func (r *Response) IsServiceUnavailable() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) IsTooManyRequests() bool
- func (r *Response) IsUnauthorized() bool
- func (r *Response) JSON(result interface{}) error
- func (r *Response) String() string
- type RetryError
- type TimeoutError
- type URLBuilder
- func (u *URLBuilder) Build() string
- func (u *URLBuilder) Param(key, value string) *URLBuilder
- func (u *URLBuilder) ParamIf(condition bool, key, value string) *URLBuilder
- func (u *URLBuilder) Params(params map[string]string) *URLBuilder
- func (u *URLBuilder) Path(segments ...string) *URLBuilder
- func (u *URLBuilder) String() string
Constants ¶
This section is empty.
Variables ¶
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 ¶
AddQueryParams adds query parameters to a URL. AddQueryParams는 URL에 쿼리 매개변수를 추가합니다.
func Delete ¶
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 ¶
DeleteContext performs a DELETE request with context using the default client. DeleteContext는 기본 클라이언트를 사용하여 context와 함께 DELETE 요청을 수행합니다.
func Download ¶
Download downloads data using the default client. Download는 기본 클라이언트를 사용하여 데이터를 다운로드합니다.
func DownloadContext ¶
DownloadContext downloads data with context using the default client. DownloadContext는 기본 클라이언트를 사용하여 context와 함께 데이터를 다운로드합니다.
func DownloadFile ¶
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 ¶
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 ¶
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 ¶
GetAllQueryParams returns all query parameters from URL. GetAllQueryParams는 URL에서 모든 쿼리 매개변수를 반환합니다.
func GetContext ¶
GetContext performs a GET request with context using the default client. GetContext는 기본 클라이언트를 사용하여 context와 함께 GET 요청을 수행합니다.
func GetQueryParam ¶
GetQueryParam returns a query parameter value from URL. GetQueryParam은 URL에서 쿼리 매개변수 값을 반환합니다.
func GetScheme ¶
GetScheme returns the scheme from a URL (http, https, etc.). GetScheme은 URL에서 스키마를 반환합니다 (http, https 등).
func GetStatusCode ¶
GetStatusCode extracts the status code from an HTTPError. Returns 0 if the error is not an HTTPError. GetStatusCode는 HTTPError에서 상태 코드를 추출합니다. 에러가 HTTPError가 아닌 경우 0을 반환합니다.
func IsAbsoluteURL ¶
IsAbsoluteURL checks if a URL is absolute (has scheme). IsAbsoluteURL은 URL이 절대 경로인지 확인합니다 (스키마가 있음).
func IsHTTPError ¶
IsHTTPError checks if an error is an HTTPError. IsHTTPError는 에러가 HTTPError인지 확인합니다.
func IsRetryError ¶
IsRetryError checks if an error is a RetryError. IsRetryError는 에러가 RetryError인지 확인합니다.
func IsTimeoutError ¶
IsTimeoutError checks if an error is a TimeoutError. IsTimeoutError는 에러가 TimeoutError인지 확인합니다.
func NormalizeURL ¶
NormalizeURL normalizes a URL (removes trailing slash, etc.). NormalizeURL은 URL을 정규화합니다 (후행 슬래시 제거 등).
func ParseForm ¶
ParseForm parses URL-encoded form data into a map. ParseForm은 URL 인코딩된 폼 데이터를 맵으로 파싱합니다.
func ParseURL ¶
ParseURL parses a URL string and returns *url.URL. ParseURL은 URL 문자열을 파싱하고 *url.URL을 반환합니다.
func Patch ¶
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 ¶
PatchContext performs a PATCH request with context using the default client. PatchContext는 기본 클라이언트를 사용하여 context와 함께 PATCH 요청을 수행합니다.
func Post ¶
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 ¶
PostContext performs a POST request with context using the default client. PostContext는 기본 클라이언트를 사용하여 context와 함께 POST 요청을 수행합니다.
func PostForm ¶
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 ¶
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 ¶
PutContext performs a PUT request with context using the default client. PutContext는 기본 클라이언트를 사용하여 context와 함께 PUT 요청을 수행합니다.
func RemoveQueryParam ¶
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 ¶
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 ¶
UploadFiles uploads multiple files using the default client. UploadFiles는 기본 클라이언트를 사용하여 여러 파일을 업로드합니다.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps http.Client with additional functionality. Client는 추가 기능을 가진 http.Client를 래핑합니다.
func NewClient ¶
NewClient creates a new HTTP client with the given options. NewClient는 주어진 옵션으로 새로운 HTTP 클라이언트를 생성합니다.
func (*Client) ClearCookies ¶
ClearCookies removes all cookies from the client's cookie jar ClearCookies는 클라이언트의 쿠키 저장소에서 모든 쿠키를 제거합니다
func (*Client) Delete ¶
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 ¶
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 ¶
Download downloads data from the given URL and returns it as bytes. Download는 주어진 URL에서 데이터를 다운로드하고 바이트로 반환합니다.
func (*Client) DownloadContext ¶
DownloadContext downloads data with context. DownloadContext는 context와 함께 데이터를 다운로드합니다.
func (*Client) DownloadFile ¶
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 ¶
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 ¶
GetCookie gets a specific cookie by name for a URL GetCookie는 URL에 대한 특정 쿠키를 이름으로 가져옵니다
func (*Client) GetCookies ¶
GetCookies returns cookies for a URL from the client's cookie jar GetCookies는 클라이언트의 쿠키 저장소에서 URL에 대한 쿠키를 반환합니다
func (*Client) HasCookie ¶
HasCookie checks if a cookie exists for a URL HasCookie는 URL에 대한 쿠키가 존재하는지 확인합니다
func (*Client) LoadCookies ¶
LoadCookies loads cookies from file if persistence is enabled LoadCookies는 지속성이 활성화된 경우 파일에서 쿠키를 로드합니다
func (*Client) Patch ¶
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 ¶
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 ¶
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 ¶
SaveCookies saves cookies to file if persistence is enabled SaveCookies는 지속성이 활성화된 경우 쿠키를 파일에 저장합니다
func (*Client) SetCookie ¶
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 및 선택적 진행 상황 콜백과 함께 파일을 업로드합니다.
type CookieJar ¶
type CookieJar struct {
// contains filtered or unexported fields
}
CookieJar manages HTTP cookies with optional persistence CookieJar는 선택적 지속성과 함께 HTTP 쿠키를 관리합니다
func NewCookieJar ¶
NewCookieJar creates a new cookie jar NewCookieJar는 새 쿠키 저장소를 생성합니다
func NewPersistentCookieJar ¶
NewPersistentCookieJar creates a cookie jar with file persistence NewPersistentCookieJar는 파일 지속성이 있는 쿠키 저장소를 생성합니다
func (*CookieJar) ClearCookies ¶
ClearCookies removes all cookies ClearCookies는 모든 쿠키를 제거합니다
func (*CookieJar) CountCookies ¶
CountCookies returns the total number of cookies for a URL CountCookies는 URL에 대한 총 쿠키 수를 반환합니다
func (*CookieJar) GetCookie ¶
GetCookie gets a specific cookie by name for a URL GetCookie는 URL에 대한 특정 쿠키를 이름으로 가져옵니다
func (*CookieJar) GetCookies ¶
GetCookies returns all cookies for a URL GetCookies는 URL에 대한 모든 쿠키를 반환합니다
func (*CookieJar) GetCookiesByDomain ¶
GetCookiesByDomain returns all cookies for a specific domain GetCookiesByDomain은 특정 도메인에 대한 모든 쿠키를 반환합니다
func (*CookieJar) HasCookie ¶
HasCookie checks if a cookie exists for a URL HasCookie는 URL에 대한 쿠키가 존재하는지 확인합니다
func (*CookieJar) LoadCookies ¶
LoadCookies loads cookies from file LoadCookies는 파일에서 쿠키를 로드합니다
func (*CookieJar) RemoveCookie ¶
RemoveCookie removes a specific cookie by name for a URL RemoveCookie는 URL에 대한 특정 쿠키를 이름으로 제거합니다
func (*CookieJar) SaveCookies ¶
SaveCookies saves cookies to file (JSON format) SaveCookies는 쿠키를 파일에 저장합니다 (JSON 형식)
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 에러를 나타냅니다.
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 ¶
WithBaseURL sets the base URL for the client. WithBaseURL은 클라이언트의 기본 URL을 설정합니다.
This is useful when making multiple requests to the same API. 동일한 API에 여러 요청을 할 때 유용합니다.
func WithBasicAuth ¶
WithBasicAuth sets Basic Authentication credentials. WithBasicAuth는 기본 인증 자격 증명을 설정합니다.
func WithBearerToken ¶
WithBearerToken sets the Bearer token for authentication. WithBearerToken은 인증을 위한 Bearer 토큰을 설정합니다.
func WithCookieJar ¶
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 ¶
WithFollowRedirects enables or disables following HTTP redirects. WithFollowRedirects는 HTTP 리디렉션 따르기를 활성화하거나 비활성화합니다.
Default: true 기본값: true
func WithHeader ¶
WithHeader sets a single custom header for the request. WithHeader는 요청에 대한 단일 사용자 정의 헤더를 설정합니다.
func WithHeaders ¶
WithHeaders sets custom headers for the request. WithHeaders는 요청에 대한 사용자 정의 헤더를 설정합니다.
func WithLogger ¶
WithLogger sets a custom logger. WithLogger는 사용자 정의 로거를 설정합니다.
func WithMaxRedirects ¶
WithMaxRedirects sets the maximum number of redirects to follow. WithMaxRedirects는 따를 최대 리디렉션 수를 설정합니다.
Default: 10 기본값: 10
func WithPersistentCookies ¶
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 WithQueryParams ¶
WithQueryParams sets query parameters for the request. WithQueryParams는 요청에 대한 쿼리 매개변수를 설정합니다.
func WithRetry ¶
WithRetry sets the maximum number of retry attempts. WithRetry는 최대 재시도 시도 횟수를 설정합니다.
Default: 3 기본값: 3
func WithRetryBackoff ¶
WithRetryBackoff sets the minimum and maximum backoff time for retries. WithRetryBackoff는 재시도에 대한 최소 및 최대 백오프 시간을 설정합니다.
Default: min=100ms, max=5s 기본값: min=100ms, max=5s
func WithTLSConfig ¶
WithTLSConfig sets a custom TLS configuration. WithTLSConfig는 사용자 정의 TLS 설정을 지정합니다.
func WithTimeout ¶
WithTimeout sets the request timeout. WithTimeout은 요청 타임아웃을 설정합니다.
Default: 30 seconds 기본값: 30초
func WithUserAgent ¶
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 ¶
Response wraps http.Response with additional functionality. Response는 추가 기능을 가진 http.Response를 래핑합니다.
func DoRaw ¶
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) ContentLength ¶
ContentLength returns the Content-Length header value. ContentLength는 Content-Length 헤더 값을 반환합니다.
func (*Response) ContentType ¶
ContentType returns the Content-Type header value. ContentType은 Content-Type 헤더 값을 반환합니다.
func (*Response) Header ¶
Header returns the value of the header with the given key. Header는 주어진 키의 헤더 값을 반환합니다.
func (*Response) IsBadGateway ¶
IsBadGateway returns true if status code is 502. IsBadGateway는 상태 코드가 502이면 true를 반환합니다.
func (*Response) IsBadRequest ¶
IsBadRequest returns true if status code is 400. IsBadRequest는 상태 코드가 400이면 true를 반환합니다.
func (*Response) IsClientError ¶
IsClientError returns true if status code is 4xx. IsClientError는 상태 코드가 4xx이면 true를 반환합니다.
func (*Response) IsCreated ¶
IsCreated returns true if status code is 201. IsCreated는 상태 코드가 201이면 true를 반환합니다.
func (*Response) IsError ¶
IsError returns true if status code is 4xx or 5xx. IsError는 상태 코드가 4xx 또는 5xx이면 true를 반환합니다.
func (*Response) IsForbidden ¶
IsForbidden returns true if status code is 403. IsForbidden는 상태 코드가 403이면 true를 반환합니다.
func (*Response) IsGatewayTimeout ¶
IsGatewayTimeout returns true if status code is 504. IsGatewayTimeout는 상태 코드가 504이면 true를 반환합니다.
func (*Response) IsInternalServerError ¶
IsInternalServerError returns true if status code is 500. IsInternalServerError는 상태 코드가 500이면 true를 반환합니다.
func (*Response) IsNoContent ¶
IsNoContent returns true if status code is 204. IsNoContent는 상태 코드가 204이면 true를 반환합니다.
func (*Response) IsNotFound ¶
IsNotFound returns true if status code is 404. IsNotFound는 상태 코드가 404이면 true를 반환합니다.
func (*Response) IsRedirect ¶
IsRedirect returns true if status code is 3xx. IsRedirect는 상태 코드가 3xx이면 true를 반환합니다.
func (*Response) IsServerError ¶
IsServerError returns true if status code is 5xx. IsServerError는 상태 코드가 5xx이면 true를 반환합니다.
func (*Response) IsServiceUnavailable ¶
IsServiceUnavailable returns true if status code is 503. IsServiceUnavailable는 상태 코드가 503이면 true를 반환합니다.
func (*Response) IsSuccess ¶
IsSuccess returns true if status code is 2xx. IsSuccess는 상태 코드가 2xx이면 true를 반환합니다.
func (*Response) IsTooManyRequests ¶
IsTooManyRequests returns true if status code is 429. IsTooManyRequests는 상태 코드가 429이면 true를 반환합니다.
func (*Response) IsUnauthorized ¶
IsUnauthorized returns true if status code is 401. IsUnauthorized는 상태 코드가 401이면 true를 반환합니다.
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와 동일).