Simple HTTP and REST client library written in Go
To install snorlax
, use go get
:
go get github.com/nickcorin/snorlax
Import the snorlax
package into your code:
package main
import "github.com/nickcorin/snorlax"
func main() {
client := snorlax.DefaultClient
}
// You can construct a DefaultClient.
client := snorlax.DefaultClient
// ...or you can use it without allocating a new Client.
res, err := snorlax.Get(context.Background(), "/example", nil)
if err != nil {
log.Fatal(err)
}
// You can configure some attibutes when constructing the client by using `ClientOption`s.
client := snorlax.NewClient(snorlax.ClientOptions{
BaseURL: "https://example.com",
})
// You can also configure the client after construction.
client.AddRequestHook(snorlax.WithHeader("X-Powered-By", "Snorlax"))
// You can also chain configuration functions.
client.SetProxyURL("https://proxy.example.com").SetHeader("X-Powered-By", "Snorlax")
// Using the DefaultClient.
res, err := snorlax.Get(context.Background(), "/example", nil)
if err != nil {
log.Fatal(err)
}
// Using a custom Client.
res, err := client.Get(context.Background(), "/example", nil)
if err != nil {
log.Fatal(err)
}
params := make(url.Values)
params.Set("name", "Snorlax")
params.Set("number", 143")
res, err := client.Get(context.Background(), "/example", params)
if err != nil {
log.Fatal(err)
}
payload := []byte("{\"name\": \"Snorlax\", \"number\": 143}")
res, err := client.Post(context.Background(), "/example", nil, bytes.NewBuffer(payload))
if err != nil {
log.Fatal(err)
}
// You can set RequestHooks which run on every request.
client.AddRequestHook(snorlax.WithHeader("Content-Type", "application/json"))
// You can also set RequestHooks to run for single requests.
username, password := "testuser", "testpassword"
res, err := client.Get(context.Background(), "/example", nil, snorlax.WithBasicAuth(username, password))
if err != nil {
log.Fatal(err)
}
// You can even define your own hooks!
func MyLoggerHook(c snorlax.Client, r *http.Request) {
log.Printf("snorlax is sending a request to %s!\n", r.URL.Path)
}
client.AddRequestHook(MyLoggerHook)
type Pokemon struct {
Name string `json:"name"`
Number int `json:"number"`
}
res, err := client.Get(context.Background(), "/example", nil)
if err != nil {
log.Fatal(err)
}
var pokemon Pokemon
if err = res.JSON(&pokemon); err != nil {
log.Fatal(err)
}
Please feel free to submit issues, fork the repositoy and send pull requests!
This project is licensed under the terms of the MIT license.