แสดงบทความที่มีป้ายกำกับ gorilla mux แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ gorilla mux แสดงบทความทั้งหมด

วันอังคารที่ 23 กุมภาพันธ์ พ.ศ. 2559

[go lang] Unit test with gorilla/mux

นั่งงมทำ unit test บน go กับ lib gorilla/mux มาครึ่งวัน เพราะเวลายิง test แล้ว มันไม่สามารถดึงตัวแปรได้

โดยปรกติเวลาเราสร้าง router บน gorilla/mux เราจะสร้าง


rtr.HandleFunc("/v1/exp/{UUID}", GetProductExp).Methods("GET")
เวลาดึงค่าก็ใช้
params := mux.Vars(r)
fmt.Println(params["UUID"]

แต่เวลาเราทำ unit test มันจะทำให้ function handle ของเราดึง var ออกมาไม่ได้เพราะถ้าเขียน unit test ปรกติจะเขียนประมาณ

func TestGetProductExp(t *testing.T) {
        fmt.Println("Testing GetProductExp")
        request, _ := http.NewRequest("GET", "/v1/exp/21a56778-6aad-4d90-aa16-6b5748a9f717", nil)
        response := httptest.NewRecorder()
        GetProductExp(response, request)
        fmt.Println(response.Body)
}

แต่เมื่อสั่ง go test ไปแล้วผลปรากฏว่า funcHandle ที่เขียนไว้ดึงค่าไม่ได้ทั้งๆที่ลอง run program ดูจริงๆแล้วลองยิง req ดูจริงๆแล้วมันก็อ่านค่าตัวแปรได้
ตอนหาข้อมูลมีคนเจอปัญหาเหมือนผมด้วย http://mrgossett.com/post/mux-vars-problem/
นั่งหาอ่านอยู่เกือบครึ่งวันกว่าจะได้คำตอบว่า lib gorilla/mux มันแปลงค่าตัวแปรให้มาอยู่ในรูป map[string]string ทำให้เวลายิงผ่าน test มันแปลงข้อมูลผิด ถ้าจะทำ unit test กับ gorilla/mux ให้เขียน test ประมาณนี้

func TestGetProductExp(t *testing.T) {
        fmt.Println("Testing GetProductExp")
        request, _ := http.NewRequest("GET", "/v1/exp/21a56778-6aad-4d90-aa16-6b5748a9f717", nil)
        response := httptest.NewRecorder()
        m := mux.NewRouter()
        m.HandleFunc("/v1/exp/{UUID}", GetProductExp)
        m.ServeHTTP(response, request)
        fmt.Println(response.Body)
}

วันอังคารที่ 10 มีนาคม พ.ศ. 2558

Golang simple web service

Go lang เป็นภาษาที่เหมาะสำหรับทำ web service มาก code ที่สั่ง start web server แค่ บรรทัดเดียวก็ทำได้ละ (บรรทัดอื่นๆเป็นการ controll route ที่จะวิ่งเข้าที่ server)
จริงๆแล้วการกำหนด route สามารถเขียนเองใน go โดยไม่ต้อง import อะไรพิเศษได้แต่ส่วนตัวแล้วผมชอบ lib ของ github.com/gorilla/mux code นี้จะเป็น code ง่ายๆที่ return ค่า "Hello world" ออกมาถ้าเราเข้าเว็บ http://localhost:8080/hello


go get github.com/gorilla/mux


package main

import (
        "fmt"
        "net/http"
        "github.com/gorilla/mux"
)

func main() {
        rtr := mux.NewRouter()
        rtr.HandleFunc("/hello",sayHi).Methods("GET")
        http.Handle("/", rtr)
        bind := ":8080"
        fmt.Printf("listening on %s...\n", bind)
        http.ListenAndServe(bind, nil)

}

func sayHi (w http.ResponseWriter, r *http.Request){
        str:="Hello world"
        w.Write([]byte (str))
}