Skip to content

Repository files navigation

HMock

Go VersionLicenseGoDocGo Report Card

HMock is a lightweight, flexible HTTP mock client for Go that helps you test your HTTP-dependent code with ease.

Features

Simple API - Works with standard http.Client interface
🔧 Customizable Responders - Define mock responses for specific requests
📝 Structured Logging - Built-in support for slog logging
🚀 Zero Dependencies - Lightweight and easy to integrate
🧪 Testing Friendly - Perfect for unit and integration tests

Installation

go get -u github.com/byterio/hmock

Usage

package main
import (
"fmt""io""log/slog""net/http""strings""github.com/byterio/hmock"
)
funcmain() {
// Create a mock client with custom respondermock:=hmock.New(hmock.Config{
Responder: func(req*http.Request) (*http.Response, error) {
return&http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader("Hello, HMock!")),
}, nil
},
Logger: slog.Default(),
})
// Use the mock clientclient:=mock.Client()
resp, err:=client.Get("https://example.com")
iferr!=nil {
panic(err)
}
deferresp.Body.Close()
body, _:=io.ReadAll(resp.Body)
fmt.Println(string(body)) // Output: Hello, HMock!
}

Advanced Usage

Custom Response Based on Request

mock:=hmock.New(hmock.Config{
Responder: func(req*http.Request) (*http.Response, error) {
ifreq.URL.Path=="/api/users" {
return&http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`[{"id":1,"name":"Byterio"}]`)),
Header: http.Header{
"Content-Type": []string{"application/json"},
},
}, nil
}
return&http.Response{
StatusCode: http.StatusNotFound,
Body: http.NoBody,
}, nil
},
})

Error Simulation

mock:=hmock.New(hmock.Config{
Responder: func(req*http.Request) (*http.Response, error) {
returnnil, fmt.Errorf("network error")
},
})

Configuration Options

OptionDescriptionDefault Value
ResponderFunction that generates responses for HTTP requestsReturns 200 OK with empty body
LoggerOptional slog.Logger for logging requests and responses (nil disables)nil (disabled)

Feedback and Contributions

If you encounter any issues or have suggestions for improvement, please open an issue on GitHub.

We welcome contributions! Fork the repository, make your changes, and submit a pull request.

Support

If you enjoy using HMock, please consider giving it a star! Your support helps others discover the project and encourages further development.

License

HMock is open-source software released under the Apache License, Version 2.0. You can find a copy of the license in the LICENSE file.

Releases

Packages

Contributors

Languages