您的位置 首页 golang

golang路由mux的介绍及基本使用

github地址:

  • #matching-routes
  • #examples
  • #examples

代码示例:

 import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"math/rand"
"net/http"
" strconv "
"strings"
)

// 定义Book的结构体
type Book  struct  {
IDstring`json:"id"`
Isbnstring`json:"isbn"`
Titlestring`json:"title"`
Author  *Author`json:"author"`
}

// 定义Author的结构体
type Author struct {
Firstnamestring`json:"firstname"`
Lastnamestring `json:"lastname"`
}

// 初始化book的切片
var books []Book

// 查询所有的Book
func getBooks(w http.ResponseWriter, r *http. Request ) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(books)
}

// 根据ID查询Book
func getBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
 params  := mux.Vars(r) // Get params
log.Println(params)
// Loop through books and find with id
for _, item := range books {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Book{})
}

// 根据Title查询
func getBookByTitle(w http.ResponseWriter, r *http.Request) {
var newBooks []Book
params := mux.Vars(r) // Get params
for _, item := range books {
if strings.Contains(item.Title, params["title"]) {
newBooks = append(newBooks, item)
}
}
json.NewEncoder(w).Encode(newBooks)
}

// 创建Book
func createBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var book Book
_ = json.NewDecoder(r.Body). Decode (&book)
book.ID = strconv.Itoa(rand.Intn(10000000)) // Mock ID - not safe
books = append(books, book);
json.NewEncoder(w).Encode(books)
}

// 修改Book
func updateBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Get params
var book Book
json.NewDecoder(r.Body).Decode(&book)
for index, item := range books {
if item.ID == params["id"] {
books[index] = book
books[index].ID = item.ID
break
}
}
json.NewEncoder(w).Encode(books)
}

// 删除Book
func deleteBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Get params
for index, item := range books {
if item.ID == params["id"] {
books = append(books[:index], books[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(books)
}

func main() {
// 初始化路由
r := mux.New Router ()

// 增加mock数据
books = append(books, Book{ID: "1", Isbn: "448743", Title: "Go语言", Author: &Author{Firstname: "John", Lastname: "Doe"}})
books = append(books, Book{ID: "2", Isbn: "448744", Title: " java 语言", Author: &Author{Firstname: " Steve ", Lastname: "Smith"}})
books = append(books, Book{ID: "3", Isbn: "448745", Title: "java程序设计", Author: &Author{Firstname: "Steve", Lastname: "Smith"}})

// 普通路由
r.HandleFunc("/api/books", getBooks).Methods("GET")
// 普通路由参数
r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
//r.HandleFunc("/api/books/byTitle/{title}", getBookByTitle).Methods("GET")
// 正则路由参数,title的查询限制为英文字母,并且是 小写字母 ,否则报:404 page not found
r.HandleFunc("/api/books/byTitle/{title:[a-z]+}", getBookByTitle).Methods("GET")

r.HandleFunc("/api/books", createBook).Methods("POST")
r.HandleFunc("/api/books/{id}", updateBook).Methods("PUT")
r.HandleFunc("/api/books/{id}", deleteBook).Methods("DELETE")
// 监听8000端口,并打出日志
log.Fatal(http.ListenAndServe(":8000", r))
}
  

运行程序,通过postman或其它http请求工具发送请求,下面是测试的结果。

1、GET请求,结果如下:

 [
    {
        "id": "1",
        "isbn": "448743",
        "title": "Go语言",
        "author": {
            "firstname": "John",
            "lastname": "Doe"
        }
    },
    {
        "id": "2",
        "isbn": "448744",
        "title": "Java语言",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    },
    {
        "id": "3",
        "isbn": "448745",
        "title": "java程序设计",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    }
]
  

2、GET请求,结果如下:

 {
    "id": "2",
    "isbn": "448744",
    "title": "Java语言",
    "author": {
        "firstname": "Steve",
        "lastname": "Smith"
    }
}
  

3、POST请求 参数(json格式):

 {
    "Isbn": "448744",
    "Title": "python语言",
    "Author": {
        "Firstname": "py",
        "Lastname": "thon"
    }
}
结果如下:
[
    {
        "id": "1",
        "isbn": "448743",
        "title": "Go语言",
        "author": {
            "firstname": "John",
            "lastname": "Doe"
        }
    },
    {
        "id": "2",
        "isbn": "448744",
        "title": "Java语言",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    },
    {
        "id": "3",
        "isbn": "448745",
        "title": "java程序设计",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    },
    {
        "id": "8498081",
        "isbn": "448744",
        "title": "python语言",
        "author": {
            "firstname": "py",
            "lastname": "thon"
        }
    }
]
新增了id为8498081的Book
  

4、DELETE请求,结果如下:

 [
    {
        "id": "1",
        "isbn": "448743",
        "title": "Go语言",
        "author": {
            "firstname": "John",
            "lastname": "Doe"
        }
    },
    {
        "id": "2",
        "isbn": "448744",
        "title": "Java语言",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    },
    {
        "id": "3",
        "isbn": "448745",
        "title": "java程序设计",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    }
]
删除了id为8498081的Book
  

5、PUT请求 , 参数(json格式):

 {
    "Isbn": "44874300",
    "Title": "Go语言-1",
    "Author": {
        "Firstname": "John-2",
        "Lastname": "Doe-2"
    }
}
结果如下:
[
    {
        "id": "1",
        "isbn": "44874300",
        "title": "Go语言-1",
        "author": {
            "firstname": "John-2",
            "lastname": "Doe-2"
        }
    },
    {
        "id": "2",
        "isbn": "448744",
        "title": "Java语言",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    },
    {
        "id": "3",
        "isbn": "448745",
        "title": "java程序设计",
        "author": {
            "firstname": "Steve",
            "lastname": "Smith"
        }
    }
]
可以看到id为1的Book已经修改了。

  

以上的例子为mux的基本使用。

代码地址:

文章来源:智云一二三科技

文章标题:golang路由mux的介绍及基本使用

文章地址:https://www.zhihuclub.com/86657.shtml

关于作者: 智云科技

热门文章

评论已关闭

29条评论

  1. Long term depression activates transcription of immediate early transcription factor genes involvement of serum response factor Elk 1

  2. Minor 1 celecoxib will increase the level or effect of flurbiprofen by acidic anionic drug competition for renal tubular clearance

  3. Library templates were prepared for sequencing using the HiSeq SR Cluster v4 Kit Illumina, Cat GD 401 4001

  4. Shi walmart high blood pressure medication Lai personally sent Will out of the gate, and now he abuse of blood pressure medication disappeared into the wind and snow on his horse, and then turned back to the house

  5. Until recently, the recommended standard duration of such therapy had been 5 years, but new research findings suggest that extending hormone therapy may benefit some patients

  6. Do not use tobramycin inhalation solution if it looks cloudy or has particles in it Dive into the research topics of Stable transfection of protein kinase C alpha cDNA in hormone dependent breast cancer cell lines

  7. When CALDOLOR is used in patients with preexisting asthma without known aspirin sensitivity, monitor patients for changes in the signs and symptoms of asthma Although I have thought about the alkaline effect of soap as being a possible effect

  8. Serious Use Alternative 1 quinidine will increase the level or effect of cortisone by P glycoprotein MDR1 efflux transporter

  9. These conflicting results suggest that further clinical studies are needed to better define the clinical effectiveness of this molecule in cancer chemoprevention

  10. Dasatinib caused a 40 reduction in the migration of MCF7 LTED and 73 in the MCF7 TAMR cells Fig 5B

  11. During his time with the Rams, Jones was part of the Fearsome Foursome along the defensive line with Merlin Olsen, Rosey Grier and Lamar Lundy

  12. In addition to regulating these physiological processes, estrogen also plays a central role in stimulating breast cancer growth

  13. Best fits were determined by minimizing the sum of squared residuals using the R function nlminb, after transforming the fraction of labeled DNA x to arcsin sqrt x

  14. Frears, smiling, said he d like the pope to see it Now he can only rely on the power of the fire in the center of the earth to suppress the cold air, otherwise, Zhao Qingzhu may be swallowed up by this cold air

网站地图