go路由库httprouter

安装

go get github.com/julienschmidt/httprouter

使用样例

RESTful API样例。使用还是非常简单方便的。

package main

import (
"github.com/julienschmidt/httprouter"
"net/http"
"fmt"
"./controllers"
"log"
)

func handlerIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}

func main() {
// Instantiate a new router
router := httprouter.New()

router.GET("/", handlerIndex)

// Get a UserController instance
uc := controllers.NewUserController()
// Get a user resource
router.GET("/users/:id", uc.GetUser)
router.POST("/users/", uc.CreateUser)
router.DELETE("/users/:id", uc.RemoveUser)
router.PUT("/users/:todoid", uc.ModifyUser)

// Fire up the server
log.Fatal(http.ListenAndServe("localhost:3000", router))
}

controllerUser.go

package controllers

import (
"net/http"
"github.com/julienschmidt/httprouter"
"encoding/json"
"fmt"

"../models"
)

type (
// UserController represents the controller for operating on the User resource
UserController struct{}
)

func NewUserController() *UserController {
return &UserController{}
}

// GetUser retrieves an individual user resource
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Stub an example user
u := models.User{
Name: "Bob Smith",
Gender: "male",
Age: 50,
Id: p.ByName("id"),
}

// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)

// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", uj)
}

// CreateUser creates a new user resource
func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Stub an user to be populated from the body
u := models.User{}

// Populate the user data
json.NewDecoder(r.Body).Decode(&u)

// Add an Id
u.Id = "foo"

// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)

// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
fmt.Fprintf(w, "%s", uj)
}

// RemoveUser removes an existing user resource
func (uc UserController) RemoveUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// TODO: only write status for now
panic("test")
w.WriteHeader(200)
}

func (uc UserController) ModifyUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Stub an user to be populated from the body
u := models.User{}

// Populate the user data
json.NewDecoder(r.Body).Decode(&u)

// Add an Id
u.Id = "foo"

// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)

// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
fmt.Fprintf(w, "%s", uj)
}

modelUser.go

package models

type (
// User represents the structure of our resource
User struct {
Name string `json:"name"`
Gender string `json:"gender"`
Age int `json:"age"`
Id string `json:"id"`
}
)