Created
November 11, 2019 08:13
-
-
Save joeke80215/169581dc44835f61defae0925c79d8a6 to your computer and use it in GitHub Desktop.
golang gin httptest example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package service | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"net/http/httptest" | |
"strings" | |
"testing" | |
"github.com/gin-gonic/gin" | |
) | |
type userINfo struct { | |
ID uint64 `json:"id"` | |
Name string `json:"name"` | |
} | |
func handler(c *gin.Context) { | |
var info userINfo | |
if err := c.ShouldBindJSON(&info); err != nil { | |
log.Panic(err) | |
} | |
fmt.Println(info) | |
c.Writer.Write([]byte(`{"status": 200}`)) | |
} | |
func TestHandler(t *testing.T) { | |
rPath := "/user" | |
router := gin.Default() | |
router.GET(rPath, handler) | |
req, _ := http.NewRequest("GET", rPath, strings.NewReader(`{"id": "1","name": "joe"}`)) | |
w := httptest.NewRecorder() | |
router.ServeHTTP(w, req) | |
t.Logf("status: %d", w.Code) | |
t.Logf("response: %s", w.Body.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!