https://github.com/memclutter/gorequests
http requests wrapper for go
https://github.com/memclutter/gorequests
golang gorequests http
Last synced: about 2 months ago
JSON representation
http requests wrapper for go
- Host: GitHub
- URL: https://github.com/memclutter/gorequests
- Owner: memclutter
- License: lgpl-2.1
- Created: 2022-07-31T18:54:33.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-01-05T21:53:04.000Z (about 3 years ago)
- Last Synced: 2024-06-21T00:12:27.741Z (almost 2 years ago)
- Topics: golang, gorequests, http
- Language: Go
- Homepage:
- Size: 55.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# gorequests
[](https://github.com/memclutter/gorequests/actions/workflows/go.yml)
[](https://codecov.io/gh/memclutter/gorequests)
http requests wrapper for go.
## Motivation
The motivation for this project was my feeling of disgust at the "convenience" of working with the golang http client.
Let's say I want to request an ip address from the ipify service (this is not advertising!).
Well, how do we do it on go? Dude, it’s easier than a steamed turnip, relax...
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
)
func GetIP() (net.IP, error) {
res, err := http.Get("https://api.ipify.org?format=json")
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf(res.Status)
}
defer res.Body.Close()
resData := make(map[string]string)
if err := json.Unmarshal(body, &resData); err != nil {
return nil, err
}
ipStr, ok := resData["ip"]
if !ok {
return nil, fmt.Errorf("not found ip")
}
ip := net.ParseIP(ipStr)
if len(ip) == 0 {
return nil, fmt.Errorf("invalid ip address '%s'", ipStr)
}
return ip, nil
}
// ...
```
cool right? I looked for alternatives, but did not find what would suit me. That's why I decided to make this project.
## Idea
If we consider the previous option, the idea is as follows
```go
package main
import (
"net"
"net/http"
"github.com/memclutter/gorequests"
)
func GetIPEasy() (ip net.IP, err error) {
err = gorequests.Request().
Method(http.MethodGet).
Url("https://api.ipify.org?format=json").
ResponseCodeOk(http.StatusOK).
ResponseJson(&ip, ".ip").
Exec()
return
}
// ...
```
or more short
```go
package main
import (
"net"
"net/http"
"github.com/memclutter/gorequests"
)
func GetIPEasy() (ip net.IP, err error) {
err = gorequests.Get("https://api.ipify.org?format=json").
ResponseCodeOk(http.StatusOK).
ResponseJson(&ip, ".ip").
Exec()
return
}
// ...
```
Wow! Now I can focus on the business logic of the application, and not the details of decoding the server response.