จริงๆแล้วการกำหนด 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))
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น