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

วันอังคารที่ 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))
}