设为首页 加入收藏

TOP

Golang:使用 httprouter 构建 API 服务器(一)
2017-10-21 06:06:53 】 浏览:2029
Tags:Golang 使用 httprouter 构建 API 服务器

https://medium.com/@gauravsingharoy/build-your-first-api-server-with-httprouter-in-golang-732b7b01f6ab
作者:Gaurav Singha Roy
译者:oopsguy.com

我 10 个月前开始成为一名 Gopher,没有回头。像许多其他 gopher 一样,我很快发现简单的语言特性对于快速构建快速、可扩展的软件非常有用。当我刚开始学习 Go 时,我正在玩不同的多路复用器(multiplexer),它可以作为 API 服务器使用。如果您像我一样有 Rails 背景,你可能也会在构建 Web 框架提供的所有功能方面遇到困难。回到多路复用器,我发现了 3 个是非常有用的好东西,即 Gorilla muxhttprouterbone(按性能从低到高排列)。即使 bone 有最佳性能和更简单的 handler 签名,但对于我来说,它仍然不够成熟,无法用于生产环境。因此,我最终使用了 httprouter。在本教程中,我将使用 httprouter 构建一个简单的 REST API 服务器。

如果你想偷懒,只想获取源码,你可以在这里[4]直接检出我的 github 仓库。

让我们开始吧。首先创建一个基本端点:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

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

func main() {
    router := httprouter.New()
    router.GET("/", Index)

    log.Fatal(http.ListenAndServe(":8080", router))
}

在上面的代码段中,Index 是一个 handler 函数,需要传入三个参数。 之后,该 handler 将在 main 函数中被注册到 GET / 路径。 现在编译并运行您的程序,转到 http:// localhost:8080,来查看您的 API 服务器。点击这里[1]获取当前代码。

现在我们可以让 API 变得复杂一点。我们现在有一个名为 Book 的实体,可以把 ISDN 字段作为唯一标识。让我们创建更多的动作,即分表代表着 Index 和 Show 动作的 GET /books 和 GET /books/:isdn。 我们的 main.go 文件此时如下:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

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

type Book struct {
    // The main identifier for the Book. This will be unique.
    ISDN   string `json:"isdn"`
    Title  string `json:"title"`
    Author string `json:"author"`
    Pages  int    `json:"pages"`
}

type JsonResponse struct {
    // Reserved field to add some meta information to the API response
    Meta interface{} `json:"meta"`
    Data interface{} `json:"data"`
}

type JsonErrorResponse struct {
    Error *ApiError `json:"error"`
}

type ApiError struct {
    Status int16  `json:"status"`
    Title  string `json:"title"`
}

// A map to store the books with the ISDN as the key
// This acts as the storage in lieu of an actual database
var bookstore = make(map[string]*Book)

// Handler for the books index action
// GET /books
func BookIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    books := []*Book{}
    for _, book := range bookstore {
        books = append(books, book)
    }
    response := &JsonResponse{Data: &books}
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(http.StatusOK)
    if err := json.NewEncoder(w).Encode(response); err != nil {
        panic(err)
    }
}

// Handler for the books Show action
// GET /books/:isdn
func BookShow(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
    isdn := params.ByName("isdn")
    book, ok := bookstore[isdn]
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    if !ok {
        // No book with the isdn in the url has been found
        w.WriteHeader(http.StatusNotFound)
        response := JsonErrorResponse{Error: &ApiError{Status: 404, Title: "Record Not Found"}}
        if err := json.NewEncoder(w).Encode(response); err != nil {
            panic(err)
        }
    }
    r
首页 上一页 1 2 3 4 下一页 尾页 1/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇golang单例模式 下一篇Go语言备忘录(3):net/http包的..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目