...

Source file src/gitlab.hexacode.org/go-libs/requests/request.go

Documentation: gitlab.hexacode.org/go-libs/requests

     1  /*
     2   * Hexacode Request
     3   * This program is Http Request Client
     4   * Package: gitlab.hexacode.org/go-libs/requests
     5   * Maintainer: Azzis Arswendo <azzis@hexacode.org>
     6   *
     7   * Copyright (C) 2023 Hexacode Teknologi Indonesia
     8   * All Rights Reserved
     9   */
    10  
    11  package requests
    12  
    13  import (
    14  	"bytes"
    15  	"fmt"
    16  	"io"
    17  	"net/http"
    18  
    19  	"gitlab.hexacode.org/go-libs/hctypes"
    20  )
    21  
    22  // Input represents the input of the Request function.
    23  type Input struct {
    24  	Method    string         // GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE
    25  	URL       string         // the URL to send the request to
    26  	URLParams hctypes.Dict   // the URL parameters to include in the request
    27  	Headers   hctypes.Dict   // the headers to include in the request
    28  	Body      hctypes.Buffer // the request body to send
    29  }
    30  
    31  // Http represents the HTTP client.
    32  type Http struct {
    33  	Headers hctypes.Dict // the headers to include in the request
    34  }
    35  
    36  // Output represents the output of the Request function.
    37  type Output struct {
    38  	Status     int            // the HTTP status code returned by the server
    39  	StatusText string         // the HTTP status text returned by the server
    40  	Headers    hctypes.Dict   // the headers returned by the server
    41  	Body       hctypes.Buffer // the body returned by the server
    42  }
    43  
    44  // DefaultHeaders is a dictionary of default headers to use in the request.
    45  var default_headers = hctypes.Dict{
    46  	"User-Agent":      hctypes.String("Requests/1.0 (go-requests)"), // HTTP User-Agent header
    47  	"Accept":          hctypes.String("*/*"),                        // HTTP Accept header
    48  	"Accept-Language": hctypes.String("en-US,en;q=0.5"),             // HTTP Accept-Language header
    49  	"DNT":             hctypes.String("1"),                          // HTTP DNT header
    50  }
    51  
    52  func base(in *Input) (*Output, error) {
    53  	url := in.URL
    54  	method := in.Method
    55  	if in.Body == nil {
    56  		in.Body = hctypes.Buffer{}
    57  	}
    58  
    59  	body := bytes.NewReader(in.Body)
    60  
    61  	if in.URLParams != nil {
    62  		url = fmt.Sprintf("%s?%s", url, in.URLParams.Copy().ToQueryString().Encode())
    63  	}
    64  
    65  	req, err := http.NewRequest(method, url, body)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  
    70  	if default_headers == nil {
    71  		default_headers = hctypes.Dict{}
    72  	}
    73  
    74  	if in.Headers == nil {
    75  		in.Headers = hctypes.Dict{}
    76  	}
    77  
    78  	for k, v := range default_headers.Copy() {
    79  		val, ok := v.(hctypes.String)
    80  		if ok {
    81  			req.Header.Set(k, string(val))
    82  		}
    83  	}
    84  
    85  	for k, v := range in.Headers.Copy() {
    86  		val, ok := v.(hctypes.String)
    87  		if ok {
    88  			req.Header.Set(k, string(val))
    89  		}
    90  	}
    91  
    92  	client := &http.Client{}
    93  	resp, err := client.Do(req)
    94  	if err != nil {
    95  		return nil, err
    96  	}
    97  	defer resp.Body.Close()
    98  
    99  	bytes, err := io.ReadAll(resp.Body)
   100  	if err != nil {
   101  		return nil, err
   102  	}
   103  
   104  	out_headers := hctypes.Dict{}
   105  
   106  	for k, v := range resp.Header {
   107  		out_headers[k] = hctypes.String(v[0])
   108  	}
   109  
   110  	return &Output{
   111  		Status:     resp.StatusCode,
   112  		StatusText: StatusText(resp.StatusCode),
   113  		Headers:    out_headers,
   114  		Body:       hctypes.Buffer(bytes),
   115  	}, nil
   116  }
   117  
   118  // SetDefaultHeaders sets the default headers to use in the request.
   119  //
   120  // headers: hctypes.Dict representing the HTTP headers.
   121  func SetDefaultHeaders(headers hctypes.Dict) {
   122  	if headers == nil {
   123  		default_headers = hctypes.Dict{}
   124  	} else {
   125  		default_headers = headers
   126  	}
   127  }
   128  
   129  // Request sends an HTTP request.
   130  //
   131  // in: *Input representing the input of the Request function.
   132  func Request(in *Input) (*Output, error) {
   133  	return base(in)
   134  }
   135  
   136  // NewHttp creates a new Http instance.
   137  //
   138  // headers: hctypes.Dict representing the HTTP headers.
   139  // Returns a pointer to Http.
   140  func NewHttp(headers hctypes.Dict) *Http {
   141  	return &Http{
   142  		Headers: headers,
   143  	}
   144  }
   145  
   146  // Request sends an HTTP request.
   147  //
   148  // method: string representing the HTTP method.
   149  // url: string representing the URL of the request.
   150  // url_param: hctypes.Dict representing the URL parameters.
   151  // body: hctypes.Buffer representing the request body.
   152  // Returns a pointer to Output and an error.
   153  func (http *Http) Request(method string, url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   154  	in := &Input{
   155  		Method:    method,
   156  		URL:       url,
   157  		URLParams: url_param,
   158  		Headers:   http.Headers,
   159  		Body:      body,
   160  	}
   161  
   162  	return base(in)
   163  }
   164  
   165  // Get sends a GET request to the specified URL.
   166  //
   167  // url: the URL to send the request to
   168  // url_param: the URL parameters to include in the request
   169  // body: the request body to send
   170  // Returns *Output and error
   171  func (http *Http) Get(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   172  	return http.Request("GET", url, url_param, body)
   173  }
   174  
   175  // Post sends a POST request to the specified URL.
   176  //
   177  // url: the URL to send the request to
   178  // url_param: the URL parameters to include in the request
   179  // body: the request body to send
   180  // Returns *Output and error
   181  func (http *Http) Post(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   182  	return http.Request("POST", url, url_param, body)
   183  }
   184  
   185  // Put sends a PUT request to the specified URL.
   186  //
   187  // url: the URL to send the request to
   188  // url_param: the URL parameters to include in the request
   189  // body: the request body to send
   190  // Returns *Output and error
   191  func (http *Http) Put(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   192  	return http.Request("PUT", url, url_param, body)
   193  }
   194  
   195  // Delete sends a DELETE request to the specified URL.
   196  //
   197  // url: the URL to send the request to
   198  // url_param: the URL parameters to include in the request
   199  // body: the request body to send
   200  // Returns *Output and error
   201  func (http *Http) Delete(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   202  	return http.Request("DELETE", url, url_param, body)
   203  }
   204  
   205  // Patch sends a PATCH request to the specified URL.
   206  //
   207  // url: the URL to send the request to
   208  // url_param: the URL parameters to include in the request
   209  // body: the request body to send
   210  // Returns *Output and error
   211  func (http *Http) Patch(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   212  	return http.Request("PATCH", url, url_param, body)
   213  }
   214  
   215  // Options sends an OPTIONS request to the specified URL.
   216  //
   217  // url: the URL to send the request to
   218  // url_param: the URL parameters to include in the request
   219  // body: the request body to send
   220  // Returns *Output and error
   221  func (http *Http) Options(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   222  	return http.Request("OPTIONS", url, url_param, body)
   223  }
   224  
   225  // Head sends a HEAD request to the specified URL.
   226  //
   227  // url: the URL to send the request to
   228  // url_param: the URL parameters to include in the request
   229  // body: the request body to send
   230  // Returns *Output and error
   231  func (http *Http) Head(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   232  	return http.Request("HEAD", url, url_param, body)
   233  }
   234  
   235  // Trace sends a TRACE request to the specified URL.
   236  //
   237  // url: the URL to send the request to
   238  // url_param: the URL parameters to include in the request
   239  // body: the request body to send
   240  // Returns *Output and error
   241  func (http *Http) Trace(url string, url_param hctypes.Dict, body hctypes.Buffer) (*Output, error) {
   242  	return http.Request("TRACE", url, url_param, body)
   243  }
   244  

View as plain text