Go Restfull Api

alfalfaw · · 953 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

安装依赖
go get -u github.com/gorilla/mux
创建项目
git clone your-repository
cd your-repository
go mod init github.com/user/your-repository

文档https://golang.org/doc/code.html

用vscode打开

如果提示是否安装插件,选择全部安装

运行
go run main.go
编译
go build

完整代码

package main

import (
    "encoding/json"
    "log"
    "math/rand"
    "net/http"
    "strconv"

    "github.com/gorilla/mux"
)

// Book Struct (Model)
type Book struct {
    ID     string  `json:"id"`
    Isbn   string  `json:"isbn"`
    Title  string  `json:"title"`
    Author *Author `json:"author"`
}

// Author Struct (Model)
type Author struct {
    Firstname string `json:"firstname"`
    Lastname  string `json:"lastname"`
}

// Init books var as slice Book struct
var books []Book

// Get All Books
func getBooks(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(books)
}

// Get Single Book
func getBook(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for _, item := range books {
        if item.ID == params["id"] {
            json.NewEncoder(w).Encode(item)
            return
        }
    }
    // return a empty book when not found
    json.NewEncoder(w).Encode(&Book{})
}

// Create a New 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)
    // 生成id
    book.ID = strconv.Itoa(rand.Intn(100000000))
    books = append(books, book)
    // return the book created
    json.NewEncoder(w).Encode(book)

}

// Update a Book
func updateBook(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for index, item := range books {
        if item.ID == params["id"] {

            books = append(books[:index], books[index+1:]...)

            var book Book
            _ = json.NewDecoder(r.Body).Decode(&book)

            book.ID = params["id"]
            books = append(books, book)
            // return the book created
            json.NewEncoder(w).Encode(book)

            return
        }

    }
    json.NewEncoder(w).Encode(books)
}

// Delete a Book
func deleteBook(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    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.NewRouter()
    books = append(books, Book{ID: "1", Isbn: "13824", Title: "Book1", Author: &Author{Firstname: "abc", Lastname: "edf"}})
    books = append(books, Book{ID: "2", Isbn: "13824", Title: "Book2", Author: &Author{Firstname: "abc", Lastname: "edf"}})
    books = append(books, Book{ID: "3", Isbn: "13824", Title: "Book3", Author: &Author{Firstname: "abc", Lastname: "edf"}})

    // Route Handlers / Endpoints
    r.HandleFunc("/api/books", getBooks).Methods("GET")
    r.HandleFunc("/api/books/{id}", getBook).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")
    // 打印严重错误
    log.Fatal(http.ListenAndServe(":8000", r))

}


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:alfalfaw

查看原文:Go Restfull Api

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

953 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传