Golang CRUD
package crud
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var (
errStatusNo200 = errors.New("http code not 200")
)
type Crud struct {
URL string
Request
}
type Request struct {
Header map[string]string
Params map[string]string
Body map[string]interface{}
}
type Response struct {
HttpCode int
Response string
Error error
}
func NewCrud(url string) *Crud {
return &Crud{URL: url}
}
func (crud *Crud) Post() Response {
httpCode, response, error := handleRequest(crud.URL, "POST", crud.Header, crud.Params, crud.Body)
resp := Response{
HttpCode: httpCode,
Response: response,
Error: error,
}
return resp
}
func (crud *Crud) Get() Response {
httpCode, response, error := handleRequest(crud.URL, "GET", crud.Header, crud.Params, crud.Body)
resp := Response{
HttpCode: httpCode,
Response: response,
Error: error,
}
return resp
}
func (crud *Crud) Put() Response {
httpCode, response, error := handleRequest(crud.URL, "PUT", crud.Header, crud.Params, crud.Body)
resp := Response{
HttpCode: httpCode,
Response: response,
Error: error,
}
return resp
}
func (crud *Crud) Delete() Response {
httpCode, response, error := handleRequest(crud.URL, "DELETE", crud.Header, crud.Params, crud.Body)
resp := Response{
HttpCode: httpCode,
Response: response,
Error: error,
}
return resp
}
func handleRequest(url string, method string, header map[string]string, params map[string]string, body map[string]interface{}) (int, string, error) {
jsonStr, _ := json.Marshal(body)
req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr))
if err != nil {
return 0, "", err
}
req.Header.Add("Content-Type", "application/json")
for key, value := range header {
req.Header.Add(key, value)
}
q := req.URL.Query()
for key, value := range params {
q.Add(key, value)
}
client := &http.Client{}
req.URL.RawQuery = q.Encode()
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, "", err
}
respBody := string(content)
return resp.StatusCode, respBody, nil
}
package crud
import (
"fmt"
"testing"
)
func TestGet(t *testing.T) {
tests := []struct {
name string
url string
header map[string]string
params map[string]string
}{
{
name: "Get",
url: "https://kimi0230.github.io",
header: nil,
params: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
curd := NewCrud(tt.url)
curd.Header = tt.header
curd.Params = tt.params
if got := curd.Get(); got.Error != nil {
t.Errorf("got = %v", got)
} else {
fmt.Println(got.HttpCode)
}
})
}
}