“Pengujian Golang HTTP” Kode Jawaban

Pengujian Golang HTTP

// main.go
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type Response struct {
	Message string `json:"message"`
}

func GetRequest(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Add("Content-Type", "application/json")

	if req.Method == "GET" && req.URL.Path == "/get" {
		data := Response{Message: "Hello World From - GET"}
		json, _ := json.Marshal(data)
		fmt.Fprint(rw, string(json))
	} else {
		data := Response{Message: "Bad Request"}
		json, _ := json.Marshal(data)
		fmt.Fprint(rw, string(json))
	}
}

func main() {
	http.HandleFunc("/get", GetRequest)

	log.Fatal(http.ListenAndServe(":8000", nil))
}


// main_test.go
package main

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestGetRequest(t *testing.T) {

	var response Response
	assert := assert.New(t)

	rq := httptest.NewRequest("GET", "/get", nil)
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(GetRequest)

	handler.ServeHTTP(rr, rq)

	err := json.Unmarshal([]byte(rr.Body.String()), &response)

	if err != nil {
		t.Error("Parse JSON Data Error")
	}

	if response.Message == "Bad Request" {
		t.Error("Request Failed")
	}

	assert.Equal(rr.Code, 200)
	assert.Equal(response.Message, "Hello World From - GET")
}
Restu Wahyu Saputra

HTTP Test Golang

library for http testing for gin framework

https://github.com/restuwahyu13/go-supertest
Restu Wahyu Saputra

Jawaban yang mirip dengan “Pengujian Golang HTTP”

Pertanyaan yang mirip dengan “Pengujian Golang HTTP”

Lebih banyak jawaban terkait untuk “Pengujian Golang HTTP” di Go

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya