HMock is a lightweight, flexible HTTP mock client for Go that helps you test your HTTP-dependent code with ease.
✨ 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
go get -u github.com/byterio/hmock
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"github.com/byterio/hmock"
)
func main() {
// Create a mock client with custom responder
mock := 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 client
client := mock.Client()
resp, err := client.Get("https://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body)) // Output: Hello, HMock!
}
mock := hmock.New(hmock.Config{
Responder: func(req *http.Request) (*http.Response, error) {
if req.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
},
})
mock := hmock.New(hmock.Config{
Responder: func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("network error")
},
})
Option | Description | Default Value |
---|---|---|
Responder |
Function that generates responses for HTTP requests | Returns 200 OK with empty body |
Logger |
Optional slog.Logger for logging requests and responses (nil disables) |
nil (disabled) |
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.
If you enjoy using HMock, please consider giving it a star! Your support helps others discover the project and encourages further development.
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.