GolangNote

Golang笔记

用goji v2 开发RESTful 服务示例

Permalink

用goji v2 开发 RESTful 服务示例

Go: RESTful 服务示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main

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

	"goji.io"
	"goji.io/pat"
	"golang.org/x/net/context"
)

type book struct {
	ISBN    string "json:isbn"
	Title   string "json:name"
	Authors string "json:author"
	Price   string "json:price"
}

var bookStore = []book{
	book{
		ISBN:    "0321774639",
		Title:   "Programming in Go: Creating Applications for the 21st Century (Developer's Library)",
		Authors: "Mark Summerfield",
		Price:   "$34.57",
	},
	book{
		ISBN:    "0134190440",
		Title:   "The Go Programming Language",
		Authors: "Alan A. A. Donovan, Brian W. Kernighan",
		Price:   "$34.57",
	},
}

func main() {
	mux := goji.NewMux()
	mux.HandleFuncC(pat.Get("/books"), allBooks)
	mux.HandleFuncC(pat.Get("/books/:isbn"), bookByISBN)
	mux.UseC(logging)
	http.ListenAndServe("localhost:8080", mux)
}

func allBooks(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	jsonOut, _ := json.Marshal(bookStore)
	fmt.Fprintf(w, string(jsonOut))
}

func bookByISBN(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	isbn := pat.Param(ctx, "isbn")
	for _, b := range bookStore {
		if b.ISBN == isbn {
			jsonOut, _ := json.Marshal(b)
			fmt.Fprintf(w, string(jsonOut))
			return
		}
	}
	w.WriteHeader(http.StatusNotFound)
}

func logging(h goji.Handler) goji.Handler {
	fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Printf("Received request: %v\n", r.URL)
		h.ServeHTTPC(ctx, w, r)
	}
	return goji.HandlerFunc(fn)
}

本文网址: https://golangnote.com/topic/134.html 转摘请注明来源

Related articles

goji v2goji 的对接

goji 是个优秀的框架,作者说以前是弄着玩的,后来较正规的按照go 的设计原则来重构,不过尽量保持原来的接口。...

goji + SSDB 构建的应用

已经过了学生的年纪,学习新东西不那么快,尝试从python 转向golang,就从博客程序开始。...

Write a Comment to "用goji v2 开发RESTful 服务示例"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms